Skip to main content

Ct Cache Lib

A specialized library developed by Credenti for efficient caching in Flask applications.


Features

  • Decorator-based caching for Flask endpoints and functions
  • Configurable Valkey connection pooling
  • Supports cache key templating with nested attribute access
  • Easy integration with Flask app lifecycle

Installation

pip install ct-cache-lib

Configuration

Add the following to your Flask app configuration:

app.config["CACHE"] = True              # Enable or disable caching
app.config["CACHE_EXPIRE_TIME"] = 60    # Default cache expiration time in seconds
app.config["CACHE_HOST"] = "localhost"  # Cache host
app.config["CACHE_PORT"] = 6379         # Cache port
app.config["CACHE_USERNAME"] = "user"   # Cache username (if required)
app.config["CACHE_PASSWORD"] = "pass"   # Cache password (if required)
app.config["CACHE_CLIENT_NAME"] = "my-client" # Cache client name

Usage

The @ct_cache.cache decorator can be applied to any function to enable caching. It supports both positional and keyword arguments.

You can also set read_only=True to prevent the cache from being updated on a cache miss. This is useful for high-priority reads where you want to avoid writing to the cache.

from flask import Flask
from ct_cache_lib import init_cache
import logging

app = Flask(__name__)
logger = logging.getLogger(__name__)

# Initialize the cache
ct_cache = init_cache(app, logger)

@app.route("/idle_time")
@ct_cache.cache(template_cache_key="idle_time_value:$idle_time", field="$idle_time")
def get_idle_time_value(idle_time: str):
    # Your function logic here
    return {"idle_time": idle_time}

Bypassing the Cache

You can dynamically bypass the cache for any decorated function by passing use_cache=False when you call it. This tells the decorator to ignore the cache and execute the function directly.

# This call will use the cache
get_idle_time_value(idle_time="123")

# This call will bypass the cache and execute the function
get_idle_time_value(idle_time="123", use_cache=False)

Updating a Cache Entry

Update a cache entry directly:

ct_cache.update(
    cache_key="idle_time_value:123",  # Actual cache key
    field="some_field",
    value={"idle_time": 123},
    is_global=False,                  # or True if the key is global
    expire_time=120                   # optional, in seconds
)

Deleting a Cache Entry

Delete a cache entry:

ct_cache.delete(
    cache_key="idle_time_value:123",  # Actual cache key, not a template
    field="some_field",
    is_global=False                   # or True if the key is global
)

Deleting Cache Entries by Patterns

Delete cache entries that match one or more patterns. This is useful for bulk invalidation of related keys.

ct_cache.delete_by_patterns(
    "user:123:*",
    "session:*:active",
    is_global=False,  # or True if the patterns are global
    batch_size=500    # optional, number of keys to delete in each batch
)

Committing and Resetting Cache

Commit cache writes after each request:

@app.after_request
def after_request(response):
    ct_cache.commit(response)
    return response

Reset cache if you need to roll back changes:

ct_cache.reset()

Cache Key Specification Examples

You can use dynamic cache keys by referencing function arguments or nested data using $.

Basic Example

@ct_cache.cache(template_cache_key="idle_time_value:$idle_time", field="$idle_time")
def get_idle_time_value(idle_time: str):
    return {"idle_time": idle_time}
  • If idle_time = 123, the cache key will be idle_time_value:123.

Keyword Argument Example

The decorator also supports keyword arguments, making it flexible for various function signatures.

@ct_cache.cache(template_cache_key="user_cache:$user_id", field="$user_id")
def get_user_by_id(user_id: int):
    # Function logic to fetch user
    return {"user_id": user_id}
  • If you call get_user_by_id(user_id=42), the cache key will be user_cache:42.

Nested Dictionary Example

@ct_cache.cache(template_cache_key="user_cache:$user.id", field="$user.id")
def get_user(user: dict):
    return user
  • If user = {"id": 01, "name": "User1"}, the cache key will be user_cache:01.

Nested Object Example

class User:
    def __init__(self, id, name):
        self.id = id
        self.name = name

@ct_cache.cache(template_cache_key="user_cache:$user.id", field="$user.id")
def get_user_obj(user: User):
    return {"id": user.id, "name": user.name}
  • If user.id = 01, the cache key will be user_cache:01.

Deeply Nested Example

@ct_cache.cache(template_cache_key="deep_cache:$data.profile.info.id", field="$data.profile.info.id")
def get_deep(data: dict):
    return data
  • If data = {"profile": {"info": {"id": 01}}}, the cache key will be deep_cache:01.

Static Key Example

@ct_cache.cache(template_cache_key="static_key")
def get_static():
    return {"result": 1}
  • The cache key will always be static_key.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ct_cache_lib-0.3.0.tar.gz (9.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ct_cache_lib-0.3.0-py3-none-any.whl (8.6 kB view details)

Uploaded Python 3

File details

Details for the file ct_cache_lib-0.3.0.tar.gz.

File metadata

  • Download URL: ct_cache_lib-0.3.0.tar.gz
  • Upload date:
  • Size: 9.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.15

File hashes

Hashes for ct_cache_lib-0.3.0.tar.gz
Algorithm Hash digest
SHA256 fd327ec9bceb00c459a8270d9bf35bbd13ef4dbecadfb1c420b83d30917d0089
MD5 66a32150d41609d9e3fa4f6c8a8cc3b4
BLAKE2b-256 9edea886bd0809da4db328b68be533c8af253ff1475f82dd3a6dcf503022d265

See more details on using hashes here.

File details

Details for the file ct_cache_lib-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: ct_cache_lib-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 8.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.15

File hashes

Hashes for ct_cache_lib-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 19c3e8a38a49145961edfc8523e2ef34c1266ef68826dbac6d5b359c86886776
MD5 aa5daea80361f486cea7bce044c111ce
BLAKE2b-256 36ed16d4c1dfcba522debcffe069383037acb65a53ea858e69c346bdd53591c0

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

0.3.0 This release

2 files

0.2.0

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page