Configure Cache Keys and Templates
masterCashews generates keys automatically using the function name, module, and arguments. You can customize this using the key parameter in decorators.
Key Templating Features
- Attribute Access: Access object attributes via
{obj.attr}. - Built-in Formatters: Use
{val:lower},{val:upper},{val:len},{val:jwt}, or{val:hash(algo)}(e.g.,sha1,md5). - Custom Formatters: Register functions via
default_formatter.register("name"). - Type Formatters: Register specific handlers for types via
default_formatter.type_format(Type). - Context Variables: Use
{@:get(var_name)}to inject variables from akey_context.
Handling self in Class Methods
When decorating class methods, self is included in the key, which often leads to undesirable results. Solutions include:
- Defining
__str__on the class. - Providing an explicit
keytemplate that usesselfattributes. - Using
@noself(cache)or@noself_cacheto exclude the instance from the key.
from cashews import cache, default_formatter, key_context
# Using built-in formatters
@cache(ttl="2h", key="user_info:{user.name:lower}:{password:hash(sha1)}")
async def get_user_info(user, password):
...
# Using context variables
@cache(ttl="2h", key="user:{@:get(client_id)}")
async def get_current_user():
pass
with key_context(client_id=135356):
await get_current_user()
# Custom type formatter
from decimal import Decimal
@default_formatter.type_format(Decimal)
def _decimal(value: Decimal) -> str:
return str(value.quantize(Decimal("0.00")))