| 1 |
Flask-Caching |
| 2 |
============= |
| 3 |
|
| 4 |
.. module:: flask_caching |
| 5 |
:noindex: |
| 6 |
|
| 7 |
Flask-Caching is an extension to `Flask`_ that adds caching support for |
| 8 |
various backends to any Flask application. By running on top of `cachelib`_ |
| 9 |
it supports all of `werkzeug`_'s original caching backends through a uniformed |
| 10 |
API. It is also possible to develop your own caching backend by subclassing |
| 11 |
:class:`flask_caching.backends.base.BaseCache` class. |
| 12 |
|
| 13 |
Version support |
| 14 |
--------------- |
| 15 |
|
| 16 |
Since 1.8, Flask-Caching supports only Python 3.5+. |
| 17 |
|
| 18 |
|
| 19 |
Installation |
| 20 |
------------ |
| 21 |
|
| 22 |
Install the extension with the following command:: |
| 23 |
|
| 24 |
$ pip install Flask-Caching |
| 25 |
|
| 26 |
|
| 27 |
Set Up |
| 28 |
------ |
| 29 |
|
| 30 |
Cache is managed through a ``Cache`` instance:: |
| 31 |
|
| 32 |
from flask import Flask |
| 33 |
from flask_caching import Cache |
| 34 |
|
| 35 |
config = { |
| 36 |
"DEBUG": True, # some Flask specific configs |
| 37 |
"CACHE_TYPE": "SimpleCache", # Flask-Caching related configs |
| 38 |
"CACHE_DEFAULT_TIMEOUT": 300 |
| 39 |
} |
| 40 |
app = Flask(__name__) |
| 41 |
# tell Flask to use the above defined config |
| 42 |
app.config.from_mapping(config) |
| 43 |
cache = Cache(app) |
| 44 |
|
| 45 |
You may also set up your ``Cache`` instance later at configuration time using |
| 46 |
**init_app** method:: |
| 47 |
|
| 48 |
cache = Cache(config={'CACHE_TYPE': 'SimpleCache'}) |
| 49 |
|
| 50 |
app = Flask(__name__) |
| 51 |
cache.init_app(app) |
| 52 |
|
| 53 |
You may also provide an alternate configuration dictionary, useful if there |
| 54 |
will be multiple ``Cache`` instances each with a different backend:: |
| 55 |
|
| 56 |
#: Method A: During instantiation of class |
| 57 |
cache = Cache(config={'CACHE_TYPE': 'SimpleCache'}) |
| 58 |
#: Method B: During init_app call |
| 59 |
cache.init_app(app, config={'CACHE_TYPE': 'SimpleCache'}) |
| 60 |
|
| 61 |
.. versionadded:: 0.7 |
| 62 |
|
| 63 |
|
| 64 |
Caching View Functions |
| 65 |
---------------------- |
| 66 |
|
| 67 |
To cache view functions you will use the :meth:`~Cache.cached` decorator. |
| 68 |
This decorator will use request.path by default for the cache_key:: |
| 69 |
|
| 70 |
@app.route("/") |
| 71 |
@cache.cached(timeout=50) |
| 72 |
def index(): |
| 73 |
return render_template('index.html') |
| 74 |
|
| 75 |
The cached decorator has another optional argument called ``unless``. This |
| 76 |
argument accepts a callable that returns True or False. If ``unless`` returns |
| 77 |
``True`` then it will bypass the caching mechanism entirely. |
| 78 |
|
| 79 |
To dynamically determine the timeout within the view, you can return `CachedResponse`, |
| 80 |
a subclass of `flask.Response`:: |
| 81 |
|
| 82 |
@app.route("/") |
| 83 |
@cache.cached() |
| 84 |
def index(): |
| 85 |
return CachedResponse( |
| 86 |
response=make_response(render_template('index.html')), |
| 87 |
timeout=50, |
| 88 |
) |
| 89 |
|
| 90 |
.. warning:: |
| 91 |
|
| 92 |
When using ``cached`` on a view, take care to put it between Flask's |
| 93 |
``@route`` decorator and your function definition. Example:: |
| 94 |
|
| 95 |
@app.route('/') |
| 96 |
@cache.cached(timeout=50) |
| 97 |
def index(): |
| 98 |
return 'Cached for 50s' |
| 99 |
|
| 100 |
If you reverse both decorator, what will be cached is the result of |
| 101 |
``@route`` decorator, and not the result of your view function. |
| 102 |
|
| 103 |
|
| 104 |
Caching Pluggable View Classes |
| 105 |
------------------------------ |
| 106 |
|
| 107 |
Flask's pluggable view classes are also supported. To cache them, use the same |
| 108 |
:meth:`~Cache.cached` decorator on the ``dispatch_request`` method:: |
| 109 |
|
| 110 |
from flask.views import View |
| 111 |
|
| 112 |
class MyView(View): |
| 113 |
@cache.cached(timeout=50) |
| 114 |
def dispatch_request(self): |
| 115 |
return 'Cached for 50s' |
| 116 |
|
| 117 |
|
| 118 |
Caching Other Functions |
| 119 |
----------------------- |
| 120 |
|
| 121 |
Using the same ``@cached`` decorator you are able to cache the result of other |
| 122 |
non-view related functions. The only stipulation is that you replace the |
| 123 |
``key_prefix``, otherwise it will use the request.path cache_key. |
| 124 |
Keys control what should be fetched from the cache. If, for example, a key |
| 125 |
does not exist in the cache, a new key-value entry will be created in the |
| 126 |
cache. Otherwise the value (i.e. the cached result) of the key will be |
| 127 |
returned:: |
| 128 |
|
| 129 |
@cache.cached(timeout=50, key_prefix='all_comments') |
| 130 |
def get_all_comments(): |
| 131 |
comments = do_serious_dbio() |
| 132 |
return [x.author for x in comments] |
| 133 |
|
| 134 |
cached_comments = get_all_comments() |
| 135 |
|
| 136 |
Make Custom `Cache Key` |
| 137 |
----------------------- |
| 138 |
|
| 139 |
Sometimes you want to define your cache key for each route. Using the same ``@cached`` |
| 140 |
decorator you are able to specify how this key is generated. This might be useful when |
| 141 |
the key for cache should not be just the default key_prefix, but has to be derived |
| 142 |
from other parameters in a request. An example usecase would be for caching POST routes, |
| 143 |
where the cache key should be derived from the data in that request, rather than just the |
| 144 |
route/view itself. |
| 145 |
|
| 146 |
``make_cache_key`` can be used to specify such a function. The function should return a |
| 147 |
string which should act like the key to the required value that is being cached:: |
| 148 |
|
| 149 |
def make_key(): |
| 150 |
"""A function which is called to derive the key for a computed value. |
| 151 |
The key in this case is the concat value of all the json request |
| 152 |
parameters. Other strategy could to use any hashing function. |
| 153 |
:returns: unique string for which the value should be cached. |
| 154 |
""" |
| 155 |
user_data = request.get_json() |
| 156 |
return ",".join([f"{key}={value}" for key, value in user_data.items()]) |
| 157 |
|
| 158 |
@app.route("/hello", methods=["POST"]) |
| 159 |
@cache.cached(timeout=60, make_cache_key=make_key) |
| 160 |
def some_func(): |
| 161 |
.... |
| 162 |
|
| 163 |
|
| 164 |
Memoization |
| 165 |
----------- |
| 166 |
|
| 167 |
See :meth:`~Cache.memoize` |
| 168 |
|
| 169 |
In memoization, the functions arguments are also included into the cache_key. |
| 170 |
|
| 171 |
.. note:: |
| 172 |
|
| 173 |
With functions that do not receive arguments, :meth:`~Cache.cached` and |
| 174 |
:meth:`~Cache.memoize` are effectively the same. |
| 175 |
|
| 176 |
Memoize is also designed for methods, since it will take into account |
| 177 |
the identity of the ``self`` or ``cls`` argument as part of the cache |
| 178 |
key. By default this identity is derived from ``repr(obj)`` (or |
| 179 |
``obj.__caching_id__()`` if the object provides one). It is **not** |
| 180 |
based on Python's built-in :func:`id`, so two distinct instances that |
| 181 |
share the same ``repr`` (for example two ORM objects loaded for the |
| 182 |
same row) will share a memoize cache entry. |
| 183 |
|
| 184 |
The theory behind memoization is that if you have a function you need |
| 185 |
to call several times in one request, it would only be calculated the first |
| 186 |
time that function is called with those arguments. For example, an sqlalchemy |
| 187 |
object that determines if a user has a role. You might need to call this |
| 188 |
function many times during a single request. To keep from hitting the database |
| 189 |
every time this information is needed you might do something like the following:: |
| 190 |
|
| 191 |
class Person(db.Model): |
| 192 |
@cache.memoize(50) |
| 193 |
def has_membership(self, role_id): |
| 194 |
return Group.query.filter_by(user=self, role_id=role_id).count() >= 1 |
| 195 |
|
| 196 |
|
| 197 |
.. warning:: |
| 198 |
|
| 199 |
Using mutable objects (classes, etc) as part of the cache key can become |
| 200 |
tricky. It is suggested to not pass in an object instance into a memoized |
| 201 |
function. However, the memoize does perform a repr() on the passed in arguments |
| 202 |
so that if the object has a __repr__ function that returns a uniquely |
| 203 |
identifying string for that object, that will be used as part of the |
| 204 |
cache key. |
| 205 |
|
| 206 |
For example, an sqlalchemy person object that returns the database id as |
| 207 |
part of the unique identifier:: |
| 208 |
|
| 209 |
class Person(db.Model): |
| 210 |
def __repr__(self): |
| 211 |
return "%s(%s)" % (self.__class__.__name__, self.id) |
| 212 |
|
| 213 |
|
| 214 |
Deleting memoize cache |
| 215 |
`````````````````````` |
| 216 |
|
| 217 |
.. versionadded:: 0.2 |
| 218 |
|
| 219 |
You might need to delete the cache on a per-function basis. Using the above |
| 220 |
example, lets say you change the user's permissions and assign them to a role, |
| 221 |
but now you need to re-calculate if they have certain memberships or not. |
| 222 |
You can do this with the :meth:`~Cache.delete_memoized` function:: |
| 223 |
|
| 224 |
cache.delete_memoized(user_has_membership) |
| 225 |
|
| 226 |
.. note:: |
| 227 |
|
| 228 |
If only the function name is given as parameter, all the memoized versions |
| 229 |
of it will be invalidated. However, you can delete specific cache by |
| 230 |
providing the same parameter values as when caching. In following |
| 231 |
example only the ``user``-role cache is deleted: |
| 232 |
|
| 233 |
.. code-block:: python |
| 234 |
|
| 235 |
user_has_membership('demo', 'admin') |
| 236 |
user_has_membership('demo', 'user') |
| 237 |
|
| 238 |
cache.delete_memoized(user_has_membership, 'demo', 'user') |
| 239 |
|
| 240 |
.. warning:: |
| 241 |
|
| 242 |
If a classmethod is memoized, you must provide the ``class`` as the first |
| 243 |
``*args`` argument. |
| 244 |
|
| 245 |
.. code-block:: python |
| 246 |
|
| 247 |
class Foobar(object): |
| 248 |
@classmethod |
| 249 |
@cache.memoize(5) |
| 250 |
def big_foo(cls, a, b): |
| 251 |
return a + b + random.randrange(0, 100000) |
| 252 |
|
| 253 |
cache.delete_memoized(Foobar.big_foo, Foobar, 5, 2) |
| 254 |
|
| 255 |
|
| 256 |
Caching Jinja2 Snippets |
| 257 |
----------------------- |
| 258 |
|
| 259 |
Usage:: |
| 260 |
|
| 261 |
{% cache [timeout [,[key1, [key2, ...]]]] %} |
| 262 |
... |
| 263 |
{% endcache %} |
| 264 |
|
| 265 |
By default, the value of "path to template file" + "block start line" is used as the cache key. |
| 266 |
Also, the key name can be set manually. Keys are concatenated together into a single string, that |
| 267 |
can be used to avoid the same block evaluating in different templates. |
| 268 |
|
| 269 |
Set the timeout to ``None`` for no timeout, but with custom keys:: |
| 270 |
|
| 271 |
{% cache None, "key" %} |
| 272 |
... |
| 273 |
{% endcache %} |
| 274 |
|
| 275 |
Set timeout to ``del`` to delete cached value:: |
| 276 |
|
| 277 |
{% cache 'del', key1 %} |
| 278 |
... |
| 279 |
{% endcache %} |
| 280 |
|
| 281 |
If keys are provided, you may easily generate the template fragment key and |
| 282 |
delete it from outside of the template context:: |
| 283 |
|
| 284 |
from flask_caching import make_template_fragment_key |
| 285 |
key = make_template_fragment_key("key1", vary_on=["key2", "key3"]) |
| 286 |
cache.delete(key) |
| 287 |
|
| 288 |
Considering we have ``render_form_field`` and ``render_submit`` macros:: |
| 289 |
|
| 290 |
{% cache 60*5 %} |
| 291 |
<div> |
| 292 |
<form> |
| 293 |
{% render_form_field(form.username) %} |
| 294 |
{% render_submit() %} |
| 295 |
</form> |
| 296 |
</div> |
| 297 |
{% endcache %} |
| 298 |
|
| 299 |
|
| 300 |
Clearing Cache |
| 301 |
-------------- |
| 302 |
|
| 303 |
See :meth:`~Cache.clear`. |
| 304 |
|
| 305 |
Here's an example script to empty your application's cache: |
| 306 |
|
| 307 |
.. code-block:: python |
| 308 |
|
| 309 |
from flask_caching import Cache |
| 310 |
|
| 311 |
from yourapp import app, your_cache_config |
| 312 |
|
| 313 |
cache = Cache() |
| 314 |
|
| 315 |
|
| 316 |
def main(): |
| 317 |
cache.init_app(app, config=your_cache_config) |
| 318 |
|
| 319 |
with app.app_context(): |
| 320 |
cache.clear() |
| 321 |
|
| 322 |
if __name__ == '__main__': |
| 323 |
main() |
| 324 |
|
| 325 |
|
| 326 |
.. warning:: |
| 327 |
|
| 328 |
Some backend implementations do not support completely clearing the cache. |
| 329 |
Also, if you're not using a key prefix, some implementations (e.g. Redis) |
| 330 |
will flush the whole database. Make sure you're not storing any other |
| 331 |
data in your caching database. |
| 332 |
|
| 333 |
|
| 334 |
Explicitly Caching Data |
| 335 |
----------------------- |
| 336 |
|
| 337 |
Data can be cached explicitly by using the proxy methods like |
| 338 |
:meth:`Cache.set`, and :meth:`Cache.get` directly. There are many other proxy |
| 339 |
methods available via the :class:`Cache` class. |
| 340 |
|
| 341 |
For example: |
| 342 |
|
| 343 |
.. code-block:: python |
| 344 |
|
| 345 |
@app.route("/html") |
| 346 |
@app.route("/html/<foo>") |
| 347 |
def html(foo=None): |
| 348 |
if foo is not None: |
| 349 |
cache.set("foo", foo) |
| 350 |
bar = cache.get("foo") |
| 351 |
return render_template_string( |
| 352 |
"<html><body>foo cache: {{bar}}</body></html>", bar=bar |
| 353 |
) |
| 354 |
|
| 355 |
|
| 356 |
Configuring Flask-Caching |
| 357 |
------------------------- |
| 358 |
|
| 359 |
The following configuration values exist for Flask-Caching: |
| 360 |
|
| 361 |
.. tabularcolumns:: |p{6.5cm}|p{8.5cm}| |
| 362 |
|
| 363 |
|
| 364 |
=============================== ================================================================== |
| 365 |
``CACHE_TYPE`` Specifies which type of caching object to |
| 366 |
use. This is an import string that will |
| 367 |
be imported and instantiated. It is |
| 368 |
assumed that the import object is a |
| 369 |
function that will return a cache |
| 370 |
object that adheres to the cache API. |
| 371 |
|
| 372 |
For flask_caching.backends.cache objects, you |
| 373 |
do not need to specify the entire |
| 374 |
import string, just one of the following |
| 375 |
names. |
| 376 |
|
| 377 |
Built-in cache types: |
| 378 |
|
| 379 |
* **NullCache** (default; old name is **null**) |
| 380 |
* **SimpleCache** (old name is **simple**) |
| 381 |
* **FileSystemCache** (old name is |
| 382 |
**filesystem**) |
| 383 |
* **RedisCache** (redis required; old name is |
| 384 |
**redis**) |
| 385 |
* **RedisSentinelCache** (redis required; old |
| 386 |
name is **redissentinel**) |
| 387 |
* **RedisClusterCache** (redis required; old |
| 388 |
name is **rediscluster**) |
| 389 |
* **UWSGICache** (uwsgi required; old name is |
| 390 |
**uwsgi**) |
| 391 |
* **MemcachedCache** (pylibmc or memcache |
| 392 |
required; old name is **memcached** or |
| 393 |
**gaememcached**) |
| 394 |
* **SASLMemcachedCache** (pylibmc required; old |
| 395 |
name is **saslmemcached**) |
| 396 |
* **SpreadSASLMemcachedCache** (pylibmc |
| 397 |
required; old name is |
| 398 |
**spreadsaslmemcached**) |
| 399 |
|
| 400 |
``CACHE_NO_NULL_WARNING`` Silence the warning message when using |
| 401 |
cache type of 'null'. |
| 402 |
``CACHE_ARGS`` Optional list to unpack and pass during |
| 403 |
the cache class instantiation. |
| 404 |
``CACHE_OPTIONS`` Optional dictionary to pass during the |
| 405 |
cache class instantiation. |
| 406 |
``CACHE_DEFAULT_TIMEOUT`` The timeout that is used if no other |
| 407 |
timeout is specified. Unit of time is |
| 408 |
seconds. Defaults to ``300``. |
| 409 |
``CACHE_IGNORE_ERRORS`` If set to any errors that occurred during the |
| 410 |
deletion process will be ignored. However, if |
| 411 |
it is set to ``False`` it will stop on the |
| 412 |
first error. This option is only relevant for |
| 413 |
the backends **FileSystemCache** and |
| 414 |
**SimpleCache**. Defaults to ``False``. |
| 415 |
``CACHE_THRESHOLD`` The maximum number of items the cache |
| 416 |
will store before it starts deleting |
| 417 |
some. Used only for SimpleCache and |
| 418 |
FileSystemCache. Defaults to ``500``. |
| 419 |
``CACHE_KEY_PREFIX`` A prefix that is added before all keys. |
| 420 |
This makes it possible to use the same |
| 421 |
memcached server for different apps. |
| 422 |
Used only for RedisCache and MemcachedCache. |
| 423 |
Defaults to ``flask_cache_``. |
| 424 |
``CACHE_SOURCE_CHECK`` The default condition applied to function |
| 425 |
decorators which controls if the source code of |
| 426 |
the function should be included when forming the |
| 427 |
hash which is used as the cache key. This |
| 428 |
ensures that if the source code changes, the |
| 429 |
cached value will not be returned when the new |
| 430 |
function is called even if the arguments are the |
| 431 |
same. Defaults to ``False``. |
| 432 |
``CACHE_UWSGI_NAME`` The name of the uwsgi caching instance to |
| 433 |
connect to, for example: mycache@localhost:3031, |
| 434 |
defaults to an empty string, which means uWSGI |
| 435 |
will cache in the local instance. If the cache |
| 436 |
is in the same instance as the werkzeug app, |
| 437 |
you only have to provide the name of the cache. |
| 438 |
``CACHE_MEMCACHED_SERVERS`` A list or a tuple of server addresses. |
| 439 |
Used only for MemcachedCache |
| 440 |
``CACHE_MEMCACHED_USERNAME`` Username for SASL authentication with memcached. |
| 441 |
Used only for SASLMemcachedCache |
| 442 |
``CACHE_MEMCACHED_PASSWORD`` Password for SASL authentication with memcached. |
| 443 |
Used only for SASLMemcachedCache |
| 444 |
``CACHE_REDIS_HOST`` A Redis server host. Used only for RedisCache. |
| 445 |
``CACHE_REDIS_PORT`` A Redis server port. Default is 6379. |
| 446 |
Used only for RedisCache. |
| 447 |
``CACHE_REDIS_PASSWORD`` A Redis password for server. Used only for RedisCache and |
| 448 |
RedisSentinelCache. |
| 449 |
``CACHE_REDIS_DB`` A Redis db (zero-based number index). Default is 0. |
| 450 |
Used only for RedisCache and RedisSentinelCache. |
| 451 |
``CACHE_REDIS_SENTINELS`` A list or a tuple of Redis sentinel addresses. Used only for |
| 452 |
RedisSentinelCache. |
| 453 |
``CACHE_REDIS_SENTINEL_MASTER`` The name of the master server in a sentinel configuration. Used |
| 454 |
only for RedisSentinelCache. |
| 455 |
``CACHE_REDIS_CLUSTER`` A string of comma-separated Redis cluster node addresses. |
| 456 |
e.g. host1:port1,host2:port2,host3:port3 . Used only for RedisClusterCache. |
| 457 |
``CACHE_DIR`` Directory to store cache. Used only for |
| 458 |
FileSystemCache. |
| 459 |
``CACHE_REDIS_URL`` URL to connect to Redis server. |
| 460 |
Example ``redis://user:password@localhost:6379/2``. Supports |
| 461 |
protocols ``redis://``, ``rediss://`` (redis over TLS) and |
| 462 |
``unix://``. See more info about URL support [here](http://redis-py.readthedocs.io/en/latest/index.html#redis.ConnectionPool.from_url). |
| 463 |
Used only for RedisCache. |
| 464 |
=============================== ================================================================== |
| 465 |
|
| 466 |
|
| 467 |
Built-in Cache Backends |
| 468 |
----------------------- |
| 469 |
|
| 470 |
|
| 471 |
NullCache |
| 472 |
````````` |
| 473 |
|
| 474 |
Set ``CACHE_TYPE`` to ``NullCache`` to use this type. The old name, ``null`` |
| 475 |
is deprecated and will be removed in Flask-Caching 2.0. |
| 476 |
|
| 477 |
Cache that doesn't cache |
| 478 |
|
| 479 |
- CACHE_DEFAULT_TIMEOUT |
| 480 |
|
| 481 |
.. versionchanged:: 1.9.1 |
| 482 |
Deprecated the old name in favour of just using the class name. |
| 483 |
|
| 484 |
|
| 485 |
SimpleCache |
| 486 |
``````````` |
| 487 |
|
| 488 |
Set ``CACHE_TYPE`` to ``SimpleCache`` to use this type. The old name, |
| 489 |
``simple`` is deprecated and will be removed in Flask-Caching 2.0. |
| 490 |
|
| 491 |
Uses a local python dictionary for caching. This is not really thread safe. |
| 492 |
|
| 493 |
Relevant configuration values |
| 494 |
|
| 495 |
- CACHE_DEFAULT_TIMEOUT |
| 496 |
- CACHE_IGNORE_ERRORS |
| 497 |
- CACHE_THRESHOLD |
| 498 |
|
| 499 |
.. versionchanged:: 1.9.1 |
| 500 |
Deprecated the old name in favour of just using the class name. |
| 501 |
|
| 502 |
|
| 503 |
FileSystemCache |
| 504 |
``````````````` |
| 505 |
|
| 506 |
Set ``CACHE_TYPE`` to ``FileSystemCache`` to use this type. The old name, |
| 507 |
``filesystem`` is deprecated and will be removed in Flask-Caching 2.0. |
| 508 |
|
| 509 |
Uses the filesystem to store cached values |
| 510 |
|
| 511 |
- CACHE_DEFAULT_TIMEOUT |
| 512 |
- CACHE_IGNORE_ERRORS |
| 513 |
- CACHE_DIR |
| 514 |
- CACHE_THRESHOLD |
| 515 |
- CACHE_OPTIONS |
| 516 |
|
| 517 |
There is a single valid entry in CACHE_OPTIONS: *mode*, which should be a 3 digit |
| 518 |
linux-style permissions octal mode. |
| 519 |
|
| 520 |
.. versionchanged:: 1.9.1 |
| 521 |
Deprecated the old name in favour of just using the class name. |
| 522 |
|
| 523 |
|
| 524 |
RedisCache |
| 525 |
`````````` |
| 526 |
|
| 527 |
Set ``CACHE_TYPE`` to ``RedisCache`` to use this type. The old name, ``redis`` |
| 528 |
is deprecated and will be removed in Flask-Caching 2.0. |
| 529 |
|
| 530 |
- CACHE_DEFAULT_TIMEOUT |
| 531 |
- CACHE_KEY_PREFIX |
| 532 |
- CACHE_OPTIONS |
| 533 |
- CACHE_REDIS_HOST |
| 534 |
- CACHE_REDIS_PORT |
| 535 |
- CACHE_REDIS_PASSWORD |
| 536 |
- CACHE_REDIS_DB |
| 537 |
- CACHE_REDIS_URL |
| 538 |
|
| 539 |
Entries in CACHE_OPTIONS are passed to the redis client as ``**kwargs`` |
| 540 |
|
| 541 |
.. versionchanged:: 1.9.1 |
| 542 |
Deprecated the old name in favour of just using the class name. |
| 543 |
|
| 544 |
|
| 545 |
RedisSentinelCache |
| 546 |
`````````````````` |
| 547 |
|
| 548 |
Set ``CACHE_TYPE`` to ``RedisSentinel`` to use this type. The old name, |
| 549 |
``redissentinel`` is deprecated and will be removed in Flask-Caching 2.0. |
| 550 |
|
| 551 |
- CACHE_KEY_PREFIX |
| 552 |
- CACHE_REDIS_SENTINELS |
| 553 |
- CACHE_REDIS_SENTINEL_MASTER |
| 554 |
- CACHE_REDIS_PASSWORD |
| 555 |
- CACHE_REDIS_SENTINEL_PASSWORD |
| 556 |
- CACHE_REDIS_DB |
| 557 |
|
| 558 |
Entries in CACHE_OPTIONS are passed to the redis client as ``**kwargs`` |
| 559 |
|
| 560 |
.. versionchanged:: 1.9.1 |
| 561 |
Deprecated the old name in favour of just using the class name. |
| 562 |
|
| 563 |
|
| 564 |
RedisClusterCache |
| 565 |
`````````````````` |
| 566 |
|
| 567 |
Set ``CACHE_TYPE`` to ``RedisClusterCache`` to use this type. The old name, |
| 568 |
``rediscluster`` is deprecated and will be removed in Flask-Caching 2.0. |
| 569 |
|
| 570 |
- CACHE_KEY_PREFIX |
| 571 |
- CACHE_REDIS_CLUSTER |
| 572 |
- CACHE_REDIS_PASSWORD |
| 573 |
|
| 574 |
Entries in CACHE_OPTIONS are passed to the redis client as ``**kwargs`` |
| 575 |
|
| 576 |
.. versionchanged:: 1.9.1 |
| 577 |
Deprecated the old name in favour of just using the class name. |
| 578 |
|
| 579 |
|
| 580 |
MemcachedCache |
| 581 |
`````````````` |
| 582 |
|
| 583 |
Set ``CACHE_TYPE`` to ``MemcachedCache`` to use this type. The old names, |
| 584 |
``memcached`` and ``gaememcached`` are deprecated and will be removed in |
| 585 |
Flask-Caching 2.0. |
| 586 |
|
| 587 |
Uses a memcached server as a backend. Supports either pylibmc or memcache or |
| 588 |
google app engine memcache library. |
| 589 |
|
| 590 |
Relevant configuration values |
| 591 |
|
| 592 |
- CACHE_DEFAULT_TIMEOUT |
| 593 |
- CACHE_KEY_PREFIX |
| 594 |
- CACHE_MEMCACHED_SERVERS |
| 595 |
|
| 596 |
|
| 597 |
.. note:: Flask-Caching does not pass additional configuration options |
| 598 |
to memcached backends. To add additional configuration to these caches, |
| 599 |
directly set the configuration options on the object after instantiation:: |
| 600 |
|
| 601 |
from flask_caching import Cache |
| 602 |
cache = Cache() |
| 603 |
|
| 604 |
# Can't configure the client yet... |
| 605 |
cache.init_app(flask_app, {"CACHE_TYPE": "memcached"}) |
| 606 |
|
| 607 |
# Break convention and set options on the _client object |
| 608 |
# directly. For pylibmc behaviors: |
| 609 |
cache.cache._client.behaviors({"tcp_nodelay": True}) |
| 610 |
|
| 611 |
Alternatively, see `Custom Cache Backends`_. |
| 612 |
|
| 613 |
.. versionchanged:: 1.9.1 |
| 614 |
Deprecated the old name in favour of just using the class name. |
| 615 |
|
| 616 |
|
| 617 |
SASLMemcachedCache |
| 618 |
`````````````````` |
| 619 |
|
| 620 |
Set ``CACHE_TYPE`` to ``SASLMemcachedCache`` to use this type. The old name, |
| 621 |
``saslmemcached`` is deprecated and will be removed in Flask-Caching 2.0. |
| 622 |
|
| 623 |
Uses a memcached server as a backend. Intended to be used with a SASL enabled |
| 624 |
connection to the memcached server. pylibmc is required and SASL must be supported |
| 625 |
by libmemcached. |
| 626 |
|
| 627 |
Relevant configuration values |
| 628 |
|
| 629 |
- CACHE_DEFAULT_TIMEOUT |
| 630 |
- CACHE_KEY_PREFIX |
| 631 |
- CACHE_OPTIONS |
| 632 |
- CACHE_MEMCACHED_SERVERS |
| 633 |
- CACHE_MEMCACHED_USERNAME |
| 634 |
- CACHE_MEMCACHED_PASSWORD |
| 635 |
|
| 636 |
.. note:: Unlike MemcachedCache, SASLMemcachedCache can be configured with |
| 637 |
CACHE_OPTIONS. |
| 638 |
|
| 639 |
.. versionadded:: 0.10 |
| 640 |
|
| 641 |
.. versionchanged:: 1.9.1 |
| 642 |
Deprecated the old name in favour of just using the class name. |
| 643 |
|
| 644 |
|
| 645 |
SpreadSASLMemcachedCache |
| 646 |
```````````````````````` |
| 647 |
|
| 648 |
Set ``CACHE_TYPE`` to ``SpreadSASLMemcachedCache`` to use this type. The old |
| 649 |
name, ``spreadsaslmemcached`` is deprecated and will be removed in |
| 650 |
Flask-Caching 2.0. |
| 651 |
|
| 652 |
Same as SASLMemcachedCache however, it has the ability to spread value across |
| 653 |
multiple keys if it is bigger than the memcached threshold which by |
| 654 |
default is 1M. Uses pickle. |
| 655 |
|
| 656 |
.. versionadded:: 0.11 |
| 657 |
|
| 658 |
.. versionchanged:: 1.1.0 |
| 659 |
Renamed ``spreadsaslmemcachedcache`` to ``spreadsaslmemcached`` for |
| 660 |
the sake of consistency. |
| 661 |
|
| 662 |
.. versionchanged:: 1.9.1 |
| 663 |
Deprecated the old name in favour of just using the class name. |
| 664 |
|
| 665 |
|
| 666 |
UWSGICache |
| 667 |
`````````` |
| 668 |
|
| 669 |
.. warning:: |
| 670 |
``UWSGICache`` is not maintained nor tested. Use at your own risk. |
| 671 |
|
| 672 |
Set ``CACHE_TYPE`` to ``flask_caching.contrib.uwsgicache.UWSGICache`` to use |
| 673 |
this type. You also have to set ``CACHE_UWSGI_NAME`` to the cache name you |
| 674 |
set in your uWSGI configuration. |
| 675 |
|
| 676 |
|
| 677 |
Custom Cache Backends |
| 678 |
--------------------- |
| 679 |
|
| 680 |
You are able to easily add your own custom cache backends by exposing a |
| 681 |
function that can instantiate and return a cache object. ``CACHE_TYPE`` will be |
| 682 |
the import string to your custom cache type. If not a subclass of |
| 683 |
:class:`flask_caching.backends.cache.BaseCache`, Flask-Caching will call it |
| 684 |
with three arguments: |
| 685 |
|
| 686 |
* ``app``, the Flask application object the cache is being initialized for |
| 687 |
* ``args``, the value of the CACHE_ARGS configuration option |
| 688 |
* ``kwargs``, the value of the CACHE_OPTIONS configuration option |
| 689 |
|
| 690 |
.. note:: ``args`` and ``kwargs`` are not expanded when instantiating the cache |
| 691 |
object, i.e. they are not passed in as ``*args`` and ``**kwargs``, but they |
| 692 |
are the exact value of the CACHE_ARGS and CACHE_OPTIONS configuration |
| 693 |
options (CACHE_ARGS, however, is converted to a list). |
| 694 |
|
| 695 |
Your custom cache should, however, subclass the |
| 696 |
:class:`flask_caching.backends.cache.BaseCache` class so it provides all the |
| 697 |
necessary methods to be usable. |
| 698 |
|
| 699 |
.. versionchanged:: 1.9.1 If your custom cache type *is* a subclass of |
| 700 |
:class:`flask_caching.backends.cache.BaseCache`, Flask-Caching will, instead |
| 701 |
of directly instantiating the class, call its ``factory`` class method with |
| 702 |
the same args as listed above. Unless overridden, ``BaseCache.factory`` |
| 703 |
simply instantiates the object without passing any arguments to it. |
| 704 |
Built-in cache classes have overridden this to mimic the old, function based |
| 705 |
cache isntantiation, so if you subclassed something that is not |
| 706 |
:class:`flask_caching.backends.cache.BaseCache`, you may want to consult the |
| 707 |
source code to see if your class is still compatible. |
| 708 |
|
| 709 |
An example implementation:: |
| 710 |
|
| 711 |
#: the_app/custom.py |
| 712 |
class RedisCache(BaseCache): |
| 713 |
def __init__(self, servers, default_timeout=500): |
| 714 |
pass |
| 715 |
|
| 716 |
@classmethod |
| 717 |
def factory(cls, app, args, kwargs): |
| 718 |
args.append(app.config['REDIS_SERVERS']) |
| 719 |
|
| 720 |
return cls(*args, **kwargs) |
| 721 |
|
| 722 |
With this example, your ``CACHE_TYPE`` might be ``the_app.custom.RedisCache`` |
| 723 |
|
| 724 |
CACHE_TYPE doesn’t have to directly point to a cache class, though. An example |
| 725 |
PylibMC cache implementation to change binary setting and provide |
| 726 |
username/password if SASL is enabled on the library:: |
| 727 |
|
| 728 |
#: the_app/custom.py |
| 729 |
def pylibmccache(app, config, args, kwargs): |
| 730 |
return pylibmc.Client(servers=config['CACHE_MEMCACHED_SERVERS'], |
| 731 |
username=config['CACHE_MEMCACHED_USERNAME'], |
| 732 |
password=config['CACHE_MEMCACHED_PASSWORD'], |
| 733 |
binary=True) |
| 734 |
|
| 735 |
With this example, your ``CACHE_TYPE`` might be ``the_app.custom.pylibmccache`` |
| 736 |
|
| 737 |
|
| 738 |
API |
| 739 |
--- |
| 740 |
|
| 741 |
.. toctree:: |
| 742 |
:maxdepth: 2 |
| 743 |
|
| 744 |
api |
| 745 |
|
| 746 |
|
| 747 |
Additional Information |
| 748 |
---------------------- |
| 749 |
|
| 750 |
.. toctree:: |
| 751 |
:maxdepth: 2 |
| 752 |
|
| 753 |
changelog |
| 754 |
license |
| 755 |
|
| 756 |
* :ref:`search` |
| 757 |
|
| 758 |
|
| 759 |
.. _Flask: http://flask.pocoo.org/ |
| 760 |
.. _werkzeug: http://werkzeug.pocoo.org/ |
| 761 |
.. _cachelib: https://github.com/pallets/cachelib |