Custom serializers¶
A cache stores bytes; a serializer converts values to bytes and back. paceapi ships JSONSerializer (which restores declared types such as Pydantic models and Decimal) and PickleSerializer. A custom one is a class with a name and three methods.
Example: compressed JSON¶
class Compressed:
"""JSON serialization with zlib compression."""
def __init__(self) -> None:
self._json = JSONSerializer()
@property
def name(self) -> str:
# Stored with every entry; entries written under another name are misses
# and are never passed to `loads`.
return "json+zlib"
def fingerprint(self, kind: type[object] | None) -> str:
# Delegate to JSONSerializer, which also detects model schema changes.
return self._json.fingerprint(kind)
def dumps(self, value: object, kind: type[object] | None) -> bytes:
return zlib.compress(self._json.dumps(value, kind))
def loads(self, data: bytes, kind: type[object] | None) -> object:
try:
plain = zlib.decompress(data)
except zlib.error as error:
# ValueError is treated as an ordinary miss; any other exception is a
# miss that is also logged as an error.
msg = "not compressed JSON"
raise ValueError(msg) from error
return self._json.loads(plain, kind)
Pass it to a Cache (for every namespace) or to a single namespace:
# Per-namespace serializer; `Cache(serializer=Compressed())` sets the default.
reports = cache.namespace("report", ttl=3600, serializer=Compressed())
@app.get("/reports/{month}")
async def report(month: str) -> Report:
return await reports.get_or_set(month, lambda: build(month), type=Report)
Full example: examples/serializer_compressed.py.
A serializer applies to values: @ns.cached, get, set and get_or_set. A response cached by @ns.response or ResponseCacheMiddleware is stored as its body bytes and does not pass through the serializer, so a serializer that compresses or encrypts does not compress or encrypt cached responses.
Compressed output is not text, so it cannot be stored through a Redis client created with decode_responses=True (see Redis / Valkey).
What is stored with each value¶
Every entry records the serializer's name, the fingerprint of the declared type, and the namespace's schema number. An entry is only read back by a serializer with the same name, for a type with the same fingerprint, under the same schema; anything else is a miss that the next write replaces. Nothing has to be cleared when storage changes:
- Changing the serializer: Entries written by the old one become misses and are never passed to the new one's
loads(). - Changing a model: Its fingerprint changes if the serializer can tell types apart.
JSONSerializercan, and the example delegates to it. A serializer that returns the same fingerprint for every type relies onschema=instead (see Deploys and schema changes).
Give each serializer a unique name, and change it whenever the meaning of its bytes changes.
Contract¶
See Serializer:
fingerprint()runs on every read and write: Compute it once per type and memoize.dumps()raisesTypeErrorfor a value it cannot write or that does not match the declared type. The error propagates to the caller, since it is a bug in the program rather than in the cache.loads()raisesValueErrorfor bytes that are not a value of the declared type; the cache treats that as an ordinary miss. Any other exception is also a miss, and is reported to cache observers as an error and logged.kindis not always a class: It is whatever was passed astype=, solist[Order]is as likely asOrder, and it isNonewhen no type was declared.
Deserialization executes store contents
A serializer reads whatever is in the store. If deserializing can execute code, as unpickling can, anyone who can write to the store can run code in your app. Only use such formats with a store that untrusted parties cannot write to.