| 1 |
.. _configuring-flask-caching: |
| 2 |
|
| 3 |
Configuration |
| 4 |
------------- |
| 5 |
|
| 6 |
The following configuration values exist for Flask-Caching: |
| 7 |
|
| 8 |
.. tabularcolumns:: |p{6.5cm}|p{8.5cm}| |
| 9 |
|
| 10 |
|
| 11 |
================================== ================================================================== |
| 12 |
``CACHE_TYPE`` Specifies which type of caching object to |
| 13 |
use. This is an import string that will |
| 14 |
be imported and instantiated. It is |
| 15 |
assumed that the import object is a |
| 16 |
function that will return a cache |
| 17 |
object that adheres to the cache API. |
| 18 |
|
| 19 |
For flask_caching.backends.cache objects, you |
| 20 |
do not need to specify the entire |
| 21 |
import string, just one of the following |
| 22 |
names. |
| 23 |
|
| 24 |
Built-in cache types: |
| 25 |
|
| 26 |
* :ref:`NullCache <nullcache>` (default) |
| 27 |
* :ref:`SimpleCache <simplecache>` |
| 28 |
* :ref:`FileSystemCache <filesystemcache>` |
| 29 |
* :ref:`RedisCache <rediscache>` (redis |
| 30 |
required) |
| 31 |
* :ref:`RedisSentinelCache |
| 32 |
<redissentinelcache>` (redis required) |
| 33 |
* :ref:`RedisClusterCache |
| 34 |
<redisclustercache>` (redis required) |
| 35 |
* :ref:`MemcachedCache <memcachedcache>` |
| 36 |
(pylibmc or memcache required) |
| 37 |
* :ref:`SASLMemcachedCache |
| 38 |
<saslmemcachedcache>` (pylibmc required) |
| 39 |
* :ref:`SpreadSASLMemcachedCache |
| 40 |
<spreadsaslmemcachedcache>` (pylibmc |
| 41 |
required) |
| 42 |
|
| 43 |
User contributed cache types: |
| 44 |
|
| 45 |
* :ref:`GoogleCloudStorageCache |
| 46 |
<googlecloudstoragecache>` |
| 47 |
(google-cloud-storage required) |
| 48 |
* :ref:`UWSGICache <uwsgicache>` (uwsgi |
| 49 |
required) |
| 50 |
|
| 51 |
``CACHE_NO_NULL_WARNING`` Silence the warning message when using |
| 52 |
cache type of 'NullCache'. |
| 53 |
``CACHE_ARGS`` Optional list to unpack and pass during |
| 54 |
the cache class instantiation. |
| 55 |
``CACHE_OPTIONS`` Optional dictionary to pass during the |
| 56 |
cache class instantiation. |
| 57 |
``CACHE_DEFAULT_TIMEOUT`` The timeout that is used if no other |
| 58 |
timeout is specified. Unit of time is |
| 59 |
seconds, a ``datetime.timedelta`` is also |
| 60 |
accepted. Defaults to ``300``. |
| 61 |
``CACHE_IGNORE_ERRORS`` If set to ``True`` any errors that occurred |
| 62 |
during the deletion process will be ignored. |
| 63 |
However, if it is set to ``False`` a |
| 64 |
``RuntimeError`` is raised if the key couldn't |
| 65 |
deleted. Applies to every backend. Defaults to ``False``. |
| 66 |
``CACHE_THRESHOLD`` The maximum number of items the cache |
| 67 |
will store before it starts deleting |
| 68 |
some. Used only for SimpleCache and |
| 69 |
FileSystemCache. Defaults to ``500``. |
| 70 |
``CACHE_KEY_PREFIX`` A prefix that is added before all keys. |
| 71 |
This makes it possible to use the same |
| 72 |
memcached server for different apps. |
| 73 |
Used only for RedisCache and MemcachedCache. |
| 74 |
Defaults to ``flask_cache_``. |
| 75 |
``CACHE_SOURCE_CHECK`` The default condition applied to function |
| 76 |
decorators which controls if the source code of |
| 77 |
the function should be included when forming the |
| 78 |
hash which is used as the cache key. This |
| 79 |
ensures that if the source code changes, the |
| 80 |
cached value will not be returned when the new |
| 81 |
function is called even if the arguments are the |
| 82 |
same. Defaults to ``False``. See |
| 83 |
:ref:`source_check <source-check>`. |
| 84 |
``CACHE_HASH_METHOD`` hash_method used for hashing cache keys. Defaults to |
| 85 |
``hashlib.sha256``. Changing it invalidates all |
| 86 |
existing cache entries. |
| 87 |
``CACHE_SERIALIZER`` The serializer the backend uses to serializer the values. |
| 88 |
If ``None`` or not set, it uses the default serializer from |
| 89 |
the backend. See :ref:`serializers` for more information. |
| 90 |
``CACHE_ENABLE_SIGNALS`` Send Flask Signals for :meth:`~Cache.cached` and |
| 91 |
:meth:`~Cache.memoize` cache hits and misses. |
| 92 |
``CACHE_UWSGI_NAME`` The name of the uwsgi caching instance to |
| 93 |
connect to, for example: mycache@localhost:3031, |
| 94 |
defaults to an empty string, which means uWSGI |
| 95 |
will cache in the local instance. If the cache |
| 96 |
is in the same instance as the werkzeug app, |
| 97 |
you only have to provide the name of the cache. |
| 98 |
``CACHE_GCS_BUCKET`` The name of the Google Cloud Storage bucket to |
| 99 |
use. The bucket must already exist. Used only |
| 100 |
for :ref:`GoogleCloudStorageCache |
| 101 |
<googlecloudstoragecache>`. |
| 102 |
``CACHE_MEMCACHED_SERVERS`` A list or a tuple of server addresses. |
| 103 |
Used only for MemcachedCache |
| 104 |
``CACHE_MEMCACHED_USERNAME`` Username for SASL authentication with memcached. |
| 105 |
Used only for SASLMemcachedCache |
| 106 |
``CACHE_MEMCACHED_PASSWORD`` Password for SASL authentication with memcached. |
| 107 |
Used only for SASLMemcachedCache |
| 108 |
``CACHE_REDIS_HOST`` A Redis server host. Used only for RedisCache. |
| 109 |
May also be an already created Redis client, see |
| 110 |
:ref:`sharing-a-redis-client`. |
| 111 |
Ignored if ``CACHE_REDIS_URL`` is set. |
| 112 |
``CACHE_REDIS_PORT`` A Redis server port. Default is 6379. |
| 113 |
Used only for RedisCache. |
| 114 |
Ignored if ``CACHE_REDIS_URL`` is set. |
| 115 |
``CACHE_REDIS_PASSWORD`` A Redis password for server. Used only for RedisCache and |
| 116 |
RedisSentinelCache. |
| 117 |
Ignored if ``CACHE_REDIS_URL`` is set. |
| 118 |
``CACHE_REDIS_DB`` A Redis db (zero-based number index). Default is 0. |
| 119 |
Used only for RedisCache and RedisSentinelCache. |
| 120 |
Ignored if ``CACHE_REDIS_URL`` already contains a |
| 121 |
database, e.g. ``redis://localhost:6379/2``. |
| 122 |
``CACHE_REDIS_SENTINELS`` A list or a tuple of Redis sentinel addresses. Used only for |
| 123 |
RedisSentinelCache. |
| 124 |
``CACHE_REDIS_SENTINEL_MASTER`` The name of the master server in a sentinel configuration. Used |
| 125 |
only for RedisSentinelCache. |
| 126 |
``CACHE_REDIS_SENTINEL_PASSWORD`` |
| 127 |
A password for authenticating with the sentinel |
| 128 |
servers themselves, as opposed to |
| 129 |
``CACHE_REDIS_PASSWORD`` which authenticates |
| 130 |
with the master. Used only for |
| 131 |
RedisSentinelCache. |
| 132 |
``CACHE_REDIS_CLUSTER`` A string of comma-separated Redis cluster node addresses. |
| 133 |
e.g. host1:port1,host2:port2,host3:port3 . Used only for RedisClusterCache. |
| 134 |
``CACHE_FILE_HASH_METHOD`` hash_method used for hashing the file names of cached |
| 135 |
entries. Defaults to ``hashlib.sha256``. |
| 136 |
``CACHE_DIR`` Directory to store cache. Used only for |
| 137 |
FileSystemCache. |
| 138 |
``CACHE_REDIS_URL`` URL to connect to Redis server. |
| 139 |
Example ``redis://user:password@localhost:6379/2``. Supports |
| 140 |
protocols ``redis://``, ``rediss://`` (redis over TLS) and |
| 141 |
``unix://``. See more info about URL support |
| 142 |
`here <http://redis-py.readthedocs.io/en/latest/index.html#redis.ConnectionPool.from_url>`_. |
| 143 |
Used only for RedisCache and RedisClusterCache. Takes |
| 144 |
precedence over the individual connection settings. |
| 145 |
================================== ================================================================== |
| 146 |
|
| 147 |
|
| 148 |
Flask-Caching will always use the `CACHE_<BACKEND>_URL` (if available) if a complete connection |
| 149 |
URI is provided. |
| 150 |
|
| 151 |
For example, ``CACHE_REDIS_URL`` and the individual connection settings are two alternative |
| 152 |
ways of describing the same connection. They are not merged: if ``CACHE_REDIS_URL`` is set, |
| 153 |
the connection is built from the URL alone and ``CACHE_REDIS_HOST``, ``CACHE_REDIS_PORT`` and |
| 154 |
``CACHE_REDIS_PASSWORD`` are silently ignored. This is intended behaviour, not a bug. |
| 155 |
|
| 156 |
For example, this configuration connects without a password, because the URL contains |
| 157 |
a database (``/0``):: |
| 158 |
|
| 159 |
config = { |
| 160 |
"CACHE_TYPE": "RedisCache", |
| 161 |
"CACHE_REDIS_URL": "redis://localhost:6379/0", |
| 162 |
"CACHE_REDIS_PASSWORD": "hunter2", # ignored |
| 163 |
} |
| 164 |
|
| 165 |
Put the credentials in the URL instead:: |
| 166 |
|
| 167 |
config = { |
| 168 |
"CACHE_TYPE": "RedisCache", |
| 169 |
"CACHE_REDIS_URL": "redis://:hunter2@localhost:6379/0", |
| 170 |
} |
| 171 |
|
| 172 |
Or drop the URL and use the individual settings only:: |
| 173 |
|
| 174 |
config = { |
| 175 |
"CACHE_TYPE": "RedisCache", |
| 176 |
"CACHE_REDIS_HOST": "localhost", |
| 177 |
"CACHE_REDIS_PORT": 6379, |
| 178 |
"CACHE_REDIS_DB": 0, |
| 179 |
"CACHE_REDIS_PASSWORD": "hunter2", |
| 180 |
} |
| 181 |
|
| 182 |
|
| 183 |
.. _sharing-a-redis-client: |
| 184 |
|
| 185 |
Sharing a Redis client or connection pool |
| 186 |
````````````````````````````````````````` |
| 187 |
|
| 188 |
``CACHE_REDIS_HOST`` does not have to be a host name. If it is set to anything |
| 189 |
other than a string, that object is used as the Redis client as-is. That makes |
| 190 |
it possible to hand ``RedisCache`` a client that was created elsewhere, so a |
| 191 |
single connection pool is shared with the rest of the application instead of |
| 192 |
every extension opening a pool of its own:: |
| 193 |
|
| 194 |
import redis |
| 195 |
from flask import Flask |
| 196 |
from flask_caching import Cache |
| 197 |
|
| 198 |
pool = redis.ConnectionPool( |
| 199 |
host="localhost", port=6379, db=0, max_connections=20 |
| 200 |
) |
| 201 |
redis_client = redis.Redis(connection_pool=pool) |
| 202 |
|
| 203 |
app = Flask(__name__) |
| 204 |
app.config.from_mapping( |
| 205 |
{ |
| 206 |
"CACHE_TYPE": "RedisCache", |
| 207 |
"CACHE_REDIS_HOST": redis_client, |
| 208 |
"CACHE_KEY_PREFIX": "myapp_", |
| 209 |
} |
| 210 |
) |
| 211 |
cache = Cache(app) |
| 212 |
|
| 213 |
The same client, or the pool it was built from, can then be passed to other |
| 214 |
extensions such as Flask-Limiter or Flask-Session and be used by the |
| 215 |
application directly, instead of each of them connecting on its own. |
| 216 |
|
| 217 |
Any object with a `redis-py`_ compatible API is accepted, not only |
| 218 |
``redis.Redis`` instances. A client returned by |
| 219 |
``redis.sentinel.Sentinel.master_for()`` works as well. |
| 220 |
|
| 221 |
A few things to keep in mind when passing in a client: |
| 222 |
|
| 223 |
- Do not set ``CACHE_REDIS_URL``. It takes precedence and builds a new client |
| 224 |
from the URL, which silently discards the one that was passed in. |
| 225 |
- ``CACHE_REDIS_PORT``, ``CACHE_REDIS_DB``, ``CACHE_REDIS_PASSWORD`` and |
| 226 |
``CACHE_OPTIONS`` are only used to build a client from a host name. They are |
| 227 |
ignored here; configure them on the client instead. ``CACHE_KEY_PREFIX`` and |
| 228 |
``CACHE_DEFAULT_TIMEOUT`` still apply, they are handled by the cache itself. |
| 229 |
- The client must not be created with ``decode_responses=True``. Cached values |
| 230 |
are pickled bytes and reading them back through a decoding client raises a |
| 231 |
``TypeError``. That option is only rejected with an explicit error when |
| 232 |
Flask-Caching creates the client itself. |
| 233 |
- Flask-Caching does not take ownership of the client. It never closes it or |
| 234 |
its connection pool, so its lifetime is up to the application. |
| 235 |
- This applies to ``RedisCache`` only. ``RedisSentinelCache`` and |
| 236 |
``RedisClusterCache`` always create their own clients from the configuration |
| 237 |
values. |
| 238 |
|
| 239 |
|
| 240 |
Using a cachelib backend directly |
| 241 |
````````````````````````````````` |
| 242 |
|
| 243 |
The built-in backends subclass their `cachelib`_ counterparts, so ``CACHE_TYPE`` |
| 244 |
can also be an import string pointing straight at a cachelib class. This is the |
| 245 |
way to use a backend that cachelib ships but Flask-Caching does not wrap, such |
| 246 |
as ``MongoDbCache``, ``DynamoDbCache`` or ``ValkeyCache``. |
| 247 |
|
| 248 |
For example, a MongoDbCache can look like this:: |
| 249 |
|
| 250 |
config = { |
| 251 |
"CACHE_TYPE": "cachelib.MongoDbCache", |
| 252 |
"CACHE_ARGS": ["mongodb://localhost:27017"], |
| 253 |
"CACHE_OPTIONS": {"db": "myapp", "collection": "cache"}, |
| 254 |
} |
| 255 |
|
| 256 |
and a ValkeyCache config like this:: |
| 257 |
|
| 258 |
config = { |
| 259 |
"CACHE_TYPE": "cachelib.valkey.ValkeyCache", |
| 260 |
"CACHE_OPTIONS": { |
| 261 |
"host": "localhost", |
| 262 |
"port": 6379, |
| 263 |
"db": 0, |
| 264 |
"key_prefix": "myapp", |
| 265 |
}, |
| 266 |
} |
| 267 |
|
| 268 |
The class is then instantiated directly: ``CACHE_ARGS`` is passed as positional |
| 269 |
arguments and ``CACHE_OPTIONS`` as keyword arguments, together with |
| 270 |
``CACHE_DEFAULT_TIMEOUT``. The other ``CACHE_*`` options (``CACHE_DIR``, |
| 271 |
``CACHE_THRESHOLD``, ``CACHE_KEY_PREFIX``, the ``CACHE_REDIS_*`` settings, ...) |
| 272 |
are only read by the built-in backends and are ignored here. Pass the |
| 273 |
equivalent cachelib arguments through ``CACHE_OPTIONS`` instead. |
| 274 |
|
| 275 |
.. _cachelib: https://github.com/pallets/cachelib |
| 276 |
.. _redis-py: https://redis.readthedocs.io/ |