Debian Codegraph @

docs/serializers.rst

raw
1 .. _serializers:
2
3 .. currentmodule:: flask_caching
4
5 Overriding the Default Serializer
6 ---------------------------------
7
8 Values are serialized by cachelib before they are handed to the backend. Every
9 backend holds a cachelib ``serializer`` instance. By default they all use ``pickle``:
10
11 - :ref:`SimpleCache <simplecache>` uses ``SimpleSerializer``
12 - :ref:`FileSystemCache <filesystemcache>` uses ``FileSystemSerializer``
13 - :ref:`RedisCache <rediscache>` uses ``RedisSerializer``
14 - :ref:`UWSGICache <uwsgicache>` uses ``UWSGISerializer``
15
16 :ref:`NullCache <nullcache>` and the memcached backends do not use one.
17
18 Set ``CACHE_SERIALIZER`` to replace it::
19
20 from cachelib.serializers import JSONSerializer
21
22 cache = Cache(app, config={
23 "CACHE_TYPE": "SimpleCache",
24 "CACHE_SERIALIZER": JSONSerializer,
25 })
26
27 The serializer must subclass ``cachelib.serializers.BaseSerializer``. It can also
28 be an already created instance of one. Anything else raises a ``ValueError`` when
29 the extension is initialized. If a backend does not use a serializer, Flask-Caching
30 will print a warning.
31
32 The custom serializer must implement ``dump``, ``dumps``, ``load`` and ``loads``.
33
34 The serializer is assigend to :attr:`Cache.cache.serializer`, for example::
35
36 cache.cache.serializer = JSONSerializer()
37
38
39 Example: Caching Unpicklable Values
40 ```````````````````````````````````
41
42 The usual reason to replace the serializer is a value that pickle refuses to
43 handle. Responses from ``send_from_directory`` are one example: they wrap an
44 open file stream, and pickling a stream raises ``TypeError``.
45
46 The simplest fix is not a serializer at all. Calling
47 :meth:`~flask.Response.freeze` reads the stream into memory and makes the
48 response picklable::
49
50 @app.route("/download")
51 @cache.cached()
52 def download():
53 response = send_from_directory(directory, filename)
54 response.freeze()
55 return response
56
57 If the problem is not confined to one view, handle it in the serializer
58 instead. Wrap the stream in a picklable object and fall back to it when
59 ``pickle.dumps`` fails::
60
61 import io
62 import pickle
63 import typing as _t
64 from os.path import basename
65 from os.path import dirname
66
67 from flask import Flask
68 from flask import send_from_directory
69 from flask_caching import Cache
70
71 from cachelib.serializers import SimpleSerializer
72
73 app = Flask(__name__)
74
75 class _PicklableStream:
76 """
77 Picklable wrapper for file like objects.
78 """
79 def __init__(self, data: bytes):
80 self._data = data
81 self._buf = io.BytesIO(data)
82
83 def read(self, size: int = -1) -> bytes:
84 return self._buf.read(size)
85
86 def __getstate__(self):
87 return {"data": self._data}
88
89 def __setstate__(self, state):
90 self.__init__(state["data"])
91
92
93 class CustomSerializer(SimpleSerializer):
94 """
95 Custom serializer that handles pickling files streams.
96
97 Read the file stream into memory and store it as bytes.
98 """
99
100 def _materialize_streams(self, value, _seen=None):
101 _seen = _seen if _seen is not None else set()
102 if id(value) in _seen:
103 return value
104 _seen.add(id(value))
105 if hasattr(value, "read") and callable(value.read):
106 return _PicklableStream(value.read())
107 if hasattr(value, "__dict__"):
108 for attr, attr_value in vars(value).items():
109 if hasattr(attr_value, "read") and callable(attr_value.read):
110 setattr(value, attr, _PicklableStream(attr_value.read()))
111 else:
112 self._materialize_streams(attr_value, _seen)
113 return value
114
115 def dumps(
116 self, value: _t.Any, protocol: int = pickle.HIGHEST_PROTOCOL
117 ) -> bytes | None:
118 try:
119 serialized = pickle.dumps(value, protocol)
120 except TypeError:
121 materialized = self._materialize_streams(value)
122 return pickle.dumps(materialized, protocol)
123 except (pickle.PickleError, pickle.PicklingError) as e:
124 self._warn(e)
125 return None
126 return serialized
127
128 serializer_cache = Cache(app, config={
129 "CACHE_TYPE": "SimpleCache",
130 "CACHE_SERIALIZER": CustomSerializer,
131 })
132
133 @app.route("/serializer-override")
134 @serializer_cache.cached()
135 def root():
136 return send_from_directory(dirname(__file__), basename(__file__))
137
138 Reading the stream loads the whole file into memory, both when caching and
139 when serving from the cache. Either approach trades memory for the cache hit.
140
141 .. note::
142
143 Adapted from a suggestion in :issue:`167`.