| 1 |
.. currentmodule:: flask_caching |
| 2 |
|
| 3 |
Usage |
| 4 |
===== |
| 5 |
|
| 6 |
Caching View Functions |
| 7 |
---------------------- |
| 8 |
|
| 9 |
To cache view functions you will use the :meth:`~Cache.cached` decorator. |
| 10 |
This decorator will use request.path by default for the cache_key:: |
| 11 |
|
| 12 |
@app.route("/") |
| 13 |
@cache.cached(timeout=50) |
| 14 |
def index(): |
| 15 |
return render_template('index.html') |
| 16 |
|
| 17 |
The cached decorator has another optional argument called ``unless``. This |
| 18 |
argument accepts a callable that returns True or False. If ``unless`` returns |
| 19 |
``True`` then it will bypass the caching mechanism entirely. |
| 20 |
|
| 21 |
To dynamically determine the timeout within the view, you can return `CachedResponse`, |
| 22 |
a subclass of `flask.Response`:: |
| 23 |
|
| 24 |
@app.route("/") |
| 25 |
@cache.cached() |
| 26 |
def index(): |
| 27 |
return CachedResponse( |
| 28 |
response=make_response(render_template('index.html')), |
| 29 |
timeout=50, |
| 30 |
) |
| 31 |
|
| 32 |
.. warning:: |
| 33 |
|
| 34 |
When using ``cached`` on a view, take care to put it between Flask's |
| 35 |
``@route`` decorator and your function definition. Example:: |
| 36 |
|
| 37 |
@app.route('/') |
| 38 |
@cache.cached(timeout=50) |
| 39 |
def index(): |
| 40 |
return 'Cached for 50s' |
| 41 |
|
| 42 |
If you reverse both decorators, what will be cached is the result of |
| 43 |
``@route`` decorator, and not the result of your view function. |
| 44 |
|
| 45 |
|
| 46 |
Deleting Cached Views |
| 47 |
````````````````````` |
| 48 |
|
| 49 |
When you want to remove the value of a cached view you can use :meth:`~Cache.delete_cached` |
| 50 |
instead of :meth:`~Cache.delete`. :meth:`~Cache.delete_cached`. builds the key of the |
| 51 |
decorated view and deletes the cache in one go:: |
| 52 |
|
| 53 |
@app.route("/user/<name>") |
| 54 |
@cache.cached(timeout=50) |
| 55 |
def user(name): |
| 56 |
return render_template("user.html", name=name) |
| 57 |
|
| 58 |
cache.delete_cached(user, "/user/Fred") |
| 59 |
|
| 60 |
Outside of a request context the view doesn't know which request was used to build |
| 61 |
the cache key. So to make it work outside of a request context you have to pass the |
| 62 |
``path``. You can also use the view function and the named arguments of the view |
| 63 |
in which case the path is built using ``url_for()``:: |
| 64 |
|
| 65 |
cache.delete_cached(user, name="bob") |
| 66 |
|
| 67 |
When you cache views with ``query_string=True`` you also have to pass the query string/args |
| 68 |
because otherwise the cache key cannot be built:: |
| 69 |
|
| 70 |
@app.route("/works") |
| 71 |
@cache.cached(timeout=50, query_string=True) |
| 72 |
def works(): |
| 73 |
return do_search(request.args) |
| 74 |
|
| 75 |
cache.delete_cached(works, "/works", "limit=15&mock=true") |
| 76 |
|
| 77 |
You can use either pass the query string as a string, a mapping or an iterable of |
| 78 |
``(key, value)`` pairs:: |
| 79 |
|
| 80 |
cache.delete_cached(works, "/works", {"limit": 15, "mock": "true"}) |
| 81 |
|
| 82 |
Additionally, ``path`` and ``query_args`` are also supported by the views ``make_cache_key()``:: |
| 83 |
|
| 84 |
key = works.make_cache_key(path="/works", query_args={"limit": 15}) |
| 85 |
|
| 86 |
.. note:: |
| 87 |
|
| 88 |
Inside a request context the view arguments are used as-is, so a view argument |
| 89 |
named ``path`` or ``query_args`` is not mistaken for the arguments above. Outside |
| 90 |
of a request context the two cannot be told apart, so such a view has to build its |
| 91 |
key from within the request context. |
| 92 |
|
| 93 |
|
| 94 |
Caching Pluggable View Classes |
| 95 |
------------------------------ |
| 96 |
|
| 97 |
Flask's pluggable view classes are also supported. To cache them, use the same |
| 98 |
:meth:`~Cache.cached` decorator on the ``dispatch_request`` method:: |
| 99 |
|
| 100 |
from flask.views import View |
| 101 |
|
| 102 |
class MyView(View): |
| 103 |
@cache.cached(timeout=50) |
| 104 |
def dispatch_request(self): |
| 105 |
return 'Cached for 50s' |
| 106 |
|
| 107 |
|
| 108 |
Caching Other Functions |
| 109 |
----------------------- |
| 110 |
|
| 111 |
Using the same ``@cached`` decorator you are able to cache the result of other |
| 112 |
non-view related functions. The only stipulation is that you replace the |
| 113 |
``key_prefix``, otherwise it will use the request.path cache_key. |
| 114 |
Keys control what should be fetched from the cache. If, for example, a key |
| 115 |
does not exist in the cache, a new key-value entry will be created in the |
| 116 |
cache. Otherwise the value (i.e. the cached result) of the key will be |
| 117 |
returned:: |
| 118 |
|
| 119 |
@cache.cached(timeout=50, key_prefix='all_comments') |
| 120 |
def get_all_comments(): |
| 121 |
comments = do_serious_dbio() |
| 122 |
return [x.author for x in comments] |
| 123 |
|
| 124 |
cached_comments = get_all_comments() |
| 125 |
|
| 126 |
Make Custom `Cache Key` |
| 127 |
----------------------- |
| 128 |
|
| 129 |
Sometimes you want to define your cache key for each route. Using the same ``@cached`` |
| 130 |
decorator you are able to specify how this key is generated. This might be useful when |
| 131 |
the key for cache should not be just the default key_prefix, but has to be derived |
| 132 |
from other parameters in a request. An example usecase would be for caching POST routes, |
| 133 |
where the cache key should be derived from the data in that request, rather than just the |
| 134 |
route/view itself. |
| 135 |
|
| 136 |
``make_cache_key`` can be used to specify such a function. The function should return a |
| 137 |
string which should act like the key to the required value that is being cached:: |
| 138 |
|
| 139 |
def make_key(): |
| 140 |
"""A function which is called to derive the key for a computed value. |
| 141 |
The key in this case is the concat value of all the json request |
| 142 |
parameters. Other strategy could to use any hashing function. |
| 143 |
:returns: unique string for which the value should be cached. |
| 144 |
""" |
| 145 |
user_data = request.get_json() |
| 146 |
return ",".join([f"{key}={value}" for key, value in user_data.items()]) |
| 147 |
|
| 148 |
@app.route("/hello", methods=["POST"]) |
| 149 |
@cache.cached(timeout=60, make_cache_key=make_key) |
| 150 |
def some_func(): |
| 151 |
.... |
| 152 |
|
| 153 |
|
| 154 |
Caching Routes With Multiple HTTP Methods |
| 155 |
----------------------------------------- |
| 156 |
|
| 157 |
The default cache key is built from ``request.path`` alone, so a route that |
| 158 |
accepts more than one method serves all of them from the same entry:: |
| 159 |
|
| 160 |
@app.route("/foo", methods=["GET", "POST"]) |
| 161 |
@cache.cached(timeout=50) |
| 162 |
def foo(): |
| 163 |
return f"body for {request.method}" |
| 164 |
|
| 165 |
Whichever method is requested first is stored under ``view//foo`` and returned |
| 166 |
for the others until the entry expires. |
| 167 |
|
| 168 |
Pass a callable ``key_prefix`` to put the method into the key:: |
| 169 |
|
| 170 |
from flask import request |
| 171 |
|
| 172 |
def method_key(): |
| 173 |
return f"view/{request.method}{request.path}" |
| 174 |
|
| 175 |
@app.route("/foo", methods=["GET", "POST"]) |
| 176 |
@cache.cached(timeout=50, key_prefix=method_key) |
| 177 |
def foo(): |
| 178 |
return f"body for {request.method}" |
| 179 |
|
| 180 |
Each method now has its own entry, ``view/GET/foo`` and ``view/POST/foo``. The |
| 181 |
callable takes no arguments and is called inside the request context, so it |
| 182 |
can read anything from ``request``. It replaces the whole prefix, ``%s`` is |
| 183 |
not substituted. |
| 184 |
|
| 185 |
This also works with ``query_string=True``:: |
| 186 |
|
| 187 |
@app.route("/works", methods=["GET", "POST"]) |
| 188 |
@cache.cached(timeout=50, query_string=True, key_prefix=method_key) |
| 189 |
def works(): |
| 190 |
return do_search(request.args) |
| 191 |
|
| 192 |
When the key depends on the request body rather than the method use |
| 193 |
``make_cache_key`` instead. See `Make Custom Cache Key`_. |
| 194 |
|
| 195 |
.. note:: |
| 196 |
|
| 197 |
Flask adds ``HEAD`` to every route that allows ``GET`` and strips the body |
| 198 |
from ``HEAD`` responses itself, so both methods can share one entry. Map |
| 199 |
``HEAD`` onto ``GET`` to avoid caching the same body twice:: |
| 200 |
|
| 201 |
def method_key(): |
| 202 |
method = "GET" if request.method == "HEAD" else request.method |
| 203 |
return f"view/{method}{request.path}" |
| 204 |
|
| 205 |
However, only do this when the view builds the same response for both methods. |
| 206 |
|
| 207 |
.. warning:: |
| 208 |
|
| 209 |
A callable ``key_prefix`` replaces the ``path`` argument of |
| 210 |
:meth:`~Cache.delete_cached` so you have to delete the entry |
| 211 |
either from a request context:: |
| 212 |
|
| 213 |
with app.test_request_context("/foo", method="POST"): |
| 214 |
cache.delete_cached(foo) |
| 215 |
|
| 216 |
or pass the key to :meth:`~Cache.delete` yourself:: |
| 217 |
|
| 218 |
cache.delete("view/POST/foo") |
| 219 |
|
| 220 |
With ``query_string=True`` only the path comes from the callable, the |
| 221 |
``query_args`` argument still applies:: |
| 222 |
|
| 223 |
with app.test_request_context("/works"): |
| 224 |
cache.delete_cached(works, query_args={"limit": 15}) |
| 225 |
|
| 226 |
|
| 227 |
Memoization |
| 228 |
----------- |
| 229 |
|
| 230 |
See :meth:`~Cache.memoize` |
| 231 |
|
| 232 |
In memoization, the functions arguments are also included into the cache_key. |
| 233 |
|
| 234 |
.. note:: |
| 235 |
|
| 236 |
With functions that do not receive arguments, :meth:`~Cache.cached` and |
| 237 |
:meth:`~Cache.memoize` are effectively the same. |
| 238 |
|
| 239 |
Memoize is also designed for methods, since it will take into account |
| 240 |
the identity of the ``self`` or ``cls`` argument as part of the cache |
| 241 |
key. By default this identity is derived from ``repr(obj)`` (or |
| 242 |
``obj.__caching_id__()`` if the object provides one). It is **not** |
| 243 |
based on Python's built-in :func:`id`, so two distinct instances that |
| 244 |
share the same ``repr`` (for example two ORM objects loaded for the |
| 245 |
same row) will share a memoize cache entry. |
| 246 |
|
| 247 |
The theory behind memoization is that if you have a function you need |
| 248 |
to call several times in one request, it would only be calculated the first |
| 249 |
time that function is called with those arguments. For example, an sqlalchemy |
| 250 |
object that determines if a user has a role. You might need to call this |
| 251 |
function many times during a single request. To keep from hitting the database |
| 252 |
every time this information is needed you might do something like the following:: |
| 253 |
|
| 254 |
class Person(db.Model): |
| 255 |
@cache.memoize(50) |
| 256 |
def has_membership(self, role_id): |
| 257 |
return Group.query.filter_by(user=self, role_id=role_id).count() >= 1 |
| 258 |
|
| 259 |
|
| 260 |
.. warning:: |
| 261 |
|
| 262 |
On a ``staticmethod`` or a ``classmethod``, ``@staticmethod`` or |
| 263 |
``@classmethod`` the route decorator must be applied at the top of the decorator stack |
| 264 |
(visually first, logically last) following the same logic as ``@route`` and ``@cached`` |
| 265 |
above:: |
| 266 |
|
| 267 |
class Person(db.Model): |
| 268 |
@staticmethod |
| 269 |
@cache.memoize(50) |
| 270 |
def calc_budget(): |
| 271 |
return do_serious_dbio() |
| 272 |
|
| 273 |
|
| 274 |
.. warning:: |
| 275 |
|
| 276 |
Using mutable objects (classes, etc) as part of the cache key can become |
| 277 |
tricky. It is suggested to not pass in an object instance into a memoized |
| 278 |
function. However, the memoize does perform a repr() on the passed in arguments |
| 279 |
so that if the object has a __repr__ function that returns a uniquely |
| 280 |
identifying string for that object, that will be used as part of the |
| 281 |
cache key. |
| 282 |
|
| 283 |
For example, an sqlalchemy person object that returns the database id as |
| 284 |
part of the unique identifier:: |
| 285 |
|
| 286 |
class Person(db.Model): |
| 287 |
def __repr__(self): |
| 288 |
return "%s(%s)" % (self.__class__.__name__, self.id) |
| 289 |
|
| 290 |
|
| 291 |
|
| 292 |
Deleting Memoize Cache |
| 293 |
`````````````````````` |
| 294 |
|
| 295 |
.. versionadded:: 0.2 |
| 296 |
|
| 297 |
You might need to delete the cache on a per-function basis. Using the above |
| 298 |
example, lets say you change the user's permissions and assign them to a role, |
| 299 |
but now you need to re-calculate if they have certain memberships or not. |
| 300 |
You can do this with the :meth:`~Cache.delete_memoized` function:: |
| 301 |
|
| 302 |
cache.delete_memoized(user_has_membership) |
| 303 |
|
| 304 |
.. note:: |
| 305 |
|
| 306 |
If only the function name is given as parameter, all the memoized versions |
| 307 |
of it will be invalidated. However, you can delete specific cache by |
| 308 |
providing the same parameter values as when caching. In following |
| 309 |
example only the ``user``-role cache is deleted: |
| 310 |
|
| 311 |
.. code-block:: python |
| 312 |
|
| 313 |
user_has_membership('demo', 'admin') |
| 314 |
user_has_membership('demo', 'user') |
| 315 |
|
| 316 |
cache.delete_memoized(user_has_membership, 'demo', 'user') |
| 317 |
|
| 318 |
.. warning:: |
| 319 |
|
| 320 |
If a classmethod is memoized, you must provide the ``class`` as the first |
| 321 |
``*args`` argument. |
| 322 |
|
| 323 |
.. code-block:: python |
| 324 |
|
| 325 |
class Foobar(object): |
| 326 |
@classmethod |
| 327 |
@cache.memoize(5) |
| 328 |
def big_foo(cls, a, b): |
| 329 |
return a + b + random.randrange(0, 100000) |
| 330 |
|
| 331 |
cache.delete_memoized(Foobar.big_foo, Foobar, 5, 2) |
| 332 |
|
| 333 |
Memoized methods are stored per instance, so how much is deleted depends on |
| 334 |
whether the method is reached through an instance or through the class: |
| 335 |
|
| 336 |
.. code-block:: python |
| 337 |
|
| 338 |
class Adder(object): |
| 339 |
@cache.memoize(5) |
| 340 |
def add(self, b): |
| 341 |
return b + random.random() |
| 342 |
|
| 343 |
adder1 = Adder() |
| 344 |
adder2 = Adder() |
| 345 |
|
| 346 |
# only the calls made on adder1, adder2 keeps its cache |
| 347 |
cache.delete_memoized(adder1.add) |
| 348 |
|
| 349 |
# every instance |
| 350 |
cache.delete_memoized(Adder.add) |
| 351 |
|
| 352 |
# only ``adder1.add(3)`` |
| 353 |
cache.delete_memoized(adder1.add, 3) |
| 354 |
|
| 355 |
Instances are told apart by their ``repr()``, which can be overridden by |
| 356 |
defining a ``__caching_id__`` method, for example to key on a user id. |
| 357 |
|
| 358 |
.. warning:: |
| 359 |
|
| 360 |
A method reached through the class does not know which instance to delete |
| 361 |
the cache for, so the instance has to be passed as the first ``*args`` |
| 362 |
argument, the same way a ``class`` is passed for a ``classmethod``: |
| 363 |
|
| 364 |
.. code-block:: python |
| 365 |
|
| 366 |
cache.delete_memoized(Adder.add, adder1, 3) |
| 367 |
|
| 368 |
.. note:: |
| 369 |
|
| 370 |
The :meth:`~Cache.delete_memoized` attribute that |
| 371 |
:meth:`~Cache.memoize` puts on the decorated function takes no arguments |
| 372 |
and always clears every instance, even when it is called through one: |
| 373 |
|
| 374 |
.. code-block:: python |
| 375 |
|
| 376 |
adder1.add.delete_memoized() # same as cache.delete_memoized(Adder.add) |
| 377 |
|
| 378 |
|
| 379 |
Decorator Options |
| 380 |
----------------- |
| 381 |
|
| 382 |
:meth:`~Cache.cached` and :meth:`~Cache.memoize` share most of their optional |
| 383 |
arguments. ``query_string`` and ``response_hit_indication`` are accepted by |
| 384 |
:meth:`~Cache.cached` only, ``make_name`` and ``args_to_ignore`` by |
| 385 |
:meth:`~Cache.memoize` only. |
| 386 |
|
| 387 |
|
| 388 |
unless |
| 389 |
`````` |
| 390 |
|
| 391 |
A callable that bypasses the cache entirely while it returns ``True``. The |
| 392 |
decorated function runs and its result is returned without the cache being |
| 393 |
read or written:: |
| 394 |
|
| 395 |
@app.route("/") |
| 396 |
@cache.cached(timeout=50, unless=lambda: current_user.is_authenticated) |
| 397 |
def index(): |
| 398 |
return render_template('index.html') |
| 399 |
|
| 400 |
If the callable accepts arguments it is called with the decorated function |
| 401 |
followed by the call's own arguments, otherwise it is called with none. |
| 402 |
|
| 403 |
|
| 404 |
forced_update |
| 405 |
````````````` |
| 406 |
|
| 407 |
A callable that refreshes the cached value while it returns ``True``, even if |
| 408 |
the entry has not expired yet. Useful for background renewal:: |
| 409 |
|
| 410 |
@app.route("/") |
| 411 |
@cache.cached(timeout=50, forced_update=lambda: feature_flags["fresh"]) |
| 412 |
def index(): |
| 413 |
return render_template('index.html') |
| 414 |
|
| 415 |
If the callable accepts arguments it is called with the call's own arguments, |
| 416 |
otherwise it is called with none. Unlike ``unless``, the result is still |
| 417 |
written to the cache. |
| 418 |
|
| 419 |
|
| 420 |
is_stale |
| 421 |
```````` |
| 422 |
|
| 423 |
.. versionadded:: 2.5.0 |
| 424 |
|
| 425 |
A callable that accepts the cached value as argument and checks whether the |
| 426 |
value is stale. If it returns ``True`` the cached value will be recomputed. |
| 427 |
Unlike ``forced_update`` it runs only on a cache hit:: |
| 428 |
|
| 429 |
def is_outdated(cached_obj): |
| 430 |
return get_last_data_updated() > cached_obj.last_update |
| 431 |
|
| 432 |
@cache.memoize(timeout=86400, is_stale=is_outdated) |
| 433 |
def build_report(user_id): |
| 434 |
return Report(user_id) |
| 435 |
|
| 436 |
If the callable accepts more than one argument, the calls own arguments are |
| 437 |
passed after the cached value:: |
| 438 |
|
| 439 |
def is_stale(report, user_id): |
| 440 |
return report.generated_at < last_import(user_id) |
| 441 |
|
| 442 |
@cache.memoize(timeout=86400, is_stale=is_stale) |
| 443 |
def build_report(user_id): |
| 444 |
return Report(user_id) |
| 445 |
|
| 446 |
``forced_update`` and ``is_stale`` can be combined. ``forced_update`` is |
| 447 |
checked first and skips the cache read entirely. |
| 448 |
|
| 449 |
|
| 450 |
response_filter |
| 451 |
``````````````` |
| 452 |
|
| 453 |
A callable invoked with the return value after the decorated function has run. |
| 454 |
If it returns ``False`` the value is not stored. Use it to keep failures out |
| 455 |
of the cache:: |
| 456 |
|
| 457 |
def only_success(response): |
| 458 |
return response.status_code == 200 |
| 459 |
|
| 460 |
@app.route("/") |
| 461 |
@cache.cached(timeout=50, response_filter=only_success) |
| 462 |
def index(): |
| 463 |
return render_template('index.html') |
| 464 |
|
| 465 |
.. versionchanged:: 2.5.0 |
| 466 |
|
| 467 |
An ``HTTPException`` raised by a view for example through |
| 468 |
:func:`flask.abort` is cached like a returned response and re-raised on a |
| 469 |
cache hit, so :meth:`~flask.Flask.errorhandler` functions still run. The |
| 470 |
filter is called with the exception's response. |
| 471 |
|
| 472 |
.. warning:: |
| 473 |
|
| 474 |
A view that aborts because of a server problem (i.e. status code ``503``) |
| 475 |
keeps returning that error until the entry expires. Use ``response_filter`` to |
| 476 |
keep such a status code out of the cache. |
| 477 |
|
| 478 |
In case a view returns just a plain string (has no ``status_code``), use a default |
| 479 |
value for the response. For example:: |
| 480 |
|
| 481 |
def not_server_error(response): |
| 482 |
return getattr(response, "status_code", 200) < 500 |
| 483 |
|
| 484 |
@app.route("/article/<slug>") |
| 485 |
@cache.cached(timeout=50, response_filter=not_server_error) |
| 486 |
def article(slug): |
| 487 |
if not backend.healthy(): |
| 488 |
abort(503) # raised again on every request |
| 489 |
|
| 490 |
article = load(slug) |
| 491 |
if article is None: |
| 492 |
abort(404) # cached and re-raised for 50 seconds |
| 493 |
|
| 494 |
return render_template("article.html", article=article) |
| 495 |
|
| 496 |
|
| 497 |
cache_none |
| 498 |
`````````` |
| 499 |
|
| 500 |
A cached ``None`` is indistinguishable from a cache miss, so by default the |
| 501 |
decorated function runs again on every call. Set ``cache_none`` to ``True`` to |
| 502 |
store ``None`` and use an extra key existence check to tell the two apart. |
| 503 |
|
| 504 |
.. warning:: |
| 505 |
|
| 506 |
This adds a second round trip to the backend, and can still return |
| 507 |
``None`` wrongly if a concurrent call writes the key between the two |
| 508 |
calls. Returning a sentinel value instead is usually the better option. |
| 509 |
|
| 510 |
|
| 511 |
.. _source-check: |
| 512 |
|
| 513 |
source_check |
| 514 |
```````````` |
| 515 |
|
| 516 |
Include the decorated function's source code in the cache key, so that editing |
| 517 |
the body invalidates values cached by the previous version even when the |
| 518 |
arguments are unchanged:: |
| 519 |
|
| 520 |
@cache.memoize(timeout=50, source_check=True) |
| 521 |
def add(a, b): |
| 522 |
return a + b |
| 523 |
|
| 524 |
Defaults to the ``CACHE_SOURCE_CHECK`` configuration value, which is ``False``. |
| 525 |
This is meant for development, where a stale value from an older revision of a |
| 526 |
function is confusing. It calls :func:`inspect.getsource` on every call, so |
| 527 |
leave it off in production. |
| 528 |
|
| 529 |
|
| 530 |
.. _hash-method: |
| 531 |
|
| 532 |
hash_method |
| 533 |
``````````` |
| 534 |
|
| 535 |
The hash constructor used when building cache keys. Defaults to the |
| 536 |
``CACHE_HASH_METHOD`` configuration value, which is :func:`hashlib.sha256`. |
| 537 |
Set it application wide:: |
| 538 |
|
| 539 |
app.config["CACHE_HASH_METHOD"] = hashlib.sha512 |
| 540 |
|
| 541 |
or override it for a single decorator:: |
| 542 |
|
| 543 |
@cache.memoize(timeout=50, hash_method=hashlib.sha512) |
| 544 |
def add(a, b): |
| 545 |
return a + b |
| 546 |
|
| 547 |
.. warning:: |
| 548 |
|
| 549 |
The cache key is derived from this hash, so changing it makes every |
| 550 |
existing cached entry unreachable. The stale entries are not deleted; they |
| 551 |
remain in the backend until they expire. |
| 552 |
|
| 553 |
Do not confuse this with ``CACHE_FILE_HASH_METHOD``, which the FileSystemCache |
| 554 |
backend uses to name the files it writes. The two are independent. |
| 555 |
|
| 556 |
|
| 557 |
query_string |
| 558 |
```````````` |
| 559 |
|
| 560 |
:meth:`~Cache.cached` only. Build the cache key from the request's query |
| 561 |
string instead of ``key_prefix``. The arguments are sorted before hashing, so |
| 562 |
``?limit=10&offset=20`` and ``?offset=20&limit=10`` share one entry:: |
| 563 |
|
| 564 |
@app.route("/search") |
| 565 |
@cache.cached(timeout=50, query_string=True) |
| 566 |
def search(): |
| 567 |
return do_search(request.args) |
| 568 |
|
| 569 |
Deleting such an entry needs the query string as well, see |
| 570 |
`Deleting cached views`_. |
| 571 |
|
| 572 |
|
| 573 |
response_hit_indication |
| 574 |
``````````````````````` |
| 575 |
|
| 576 |
:meth:`~Cache.cached` only. When ``True``, responses that were served from the |
| 577 |
cache carry a ``hit_cache`` header. Responses produced by running the view do |
| 578 |
not:: |
| 579 |
|
| 580 |
@app.route("/") |
| 581 |
@cache.cached(timeout=50, response_hit_indication=True) |
| 582 |
def index(): |
| 583 |
return render_template('index.html') |
| 584 |
|
| 585 |
.. versionadded:: 2.3.0 |
| 586 |
|
| 587 |
|
| 588 |
make_name |
| 589 |
````````` |
| 590 |
|
| 591 |
:meth:`~Cache.memoize` only. A callable that receives the name of the |
| 592 |
decorated function and returns the name to use in the cache key. Without it |
| 593 |
the function name is used. |
| 594 |
|
| 595 |
|
| 596 |
args_to_ignore |
| 597 |
`````````````` |
| 598 |
|
| 599 |
:meth:`~Cache.memoize` only. Names of arguments to leave out of the cache key, |
| 600 |
so that calls differing only in those arguments share an entry:: |
| 601 |
|
| 602 |
@cache.memoize(timeout=50, args_to_ignore=["session"]) |
| 603 |
def get_user(session, user_id): |
| 604 |
return session.query(User).get(user_id) |
| 605 |
|
| 606 |
.. versionadded:: 1.10 |
| 607 |
|
| 608 |
|
| 609 |
Caching Jinja2 Snippets |
| 610 |
----------------------- |
| 611 |
|
| 612 |
Usage:: |
| 613 |
|
| 614 |
{% cache [timeout [,[key1, [key2, ...]]]] %} |
| 615 |
... |
| 616 |
{% endcache %} |
| 617 |
|
| 618 |
By default, the value of "path to template file" + "block start line" is used as the cache key. |
| 619 |
Also, the key name can be set manually. Keys are concatenated together into a single string, that |
| 620 |
can be used to avoid the same block evaluating in different templates. |
| 621 |
|
| 622 |
Set the timeout to ``None`` for no timeout, but with custom keys:: |
| 623 |
|
| 624 |
{% cache None, "key" %} |
| 625 |
... |
| 626 |
{% endcache %} |
| 627 |
|
| 628 |
Set timeout to ``del`` to delete cached value:: |
| 629 |
|
| 630 |
{% cache 'del', key1 %} |
| 631 |
... |
| 632 |
{% endcache %} |
| 633 |
|
| 634 |
If keys are provided, you may easily generate the template fragment key and |
| 635 |
delete it from outside of the template context:: |
| 636 |
|
| 637 |
from flask_caching import make_template_fragment_key |
| 638 |
key = make_template_fragment_key("key1", vary_on=["key2", "key3"]) |
| 639 |
cache.delete(key) |
| 640 |
|
| 641 |
Considering we have ``render_form_field`` and ``render_submit`` macros:: |
| 642 |
|
| 643 |
{% cache 60*5 %} |
| 644 |
<div> |
| 645 |
<form> |
| 646 |
{% render_form_field(form.username) %} |
| 647 |
{% render_submit() %} |
| 648 |
</form> |
| 649 |
</div> |
| 650 |
{% endcache %} |
| 651 |
|
| 652 |
|
| 653 |
Clearing Cache |
| 654 |
-------------- |
| 655 |
|
| 656 |
See :meth:`~Cache.clear`. To delete the entry of a single view see |
| 657 |
`Deleting cached views`_. |
| 658 |
|
| 659 |
Here's an example script to empty your application's cache: |
| 660 |
|
| 661 |
.. code-block:: python |
| 662 |
|
| 663 |
from flask_caching import Cache |
| 664 |
|
| 665 |
from yourapp import app, your_cache_config |
| 666 |
|
| 667 |
cache = Cache() |
| 668 |
|
| 669 |
|
| 670 |
def main(): |
| 671 |
cache.init_app(app, config=your_cache_config) |
| 672 |
|
| 673 |
with app.app_context(): |
| 674 |
cache.clear() |
| 675 |
|
| 676 |
if __name__ == '__main__': |
| 677 |
main() |
| 678 |
|
| 679 |
|
| 680 |
.. warning:: |
| 681 |
|
| 682 |
Some backend implementations do not support completely clearing the cache. |
| 683 |
Also, if you're not using a key prefix, some implementations (e.g. Redis) |
| 684 |
will flush the whole database. Make sure you're not storing any other |
| 685 |
data in your caching database. |
| 686 |
|
| 687 |
|
| 688 |
Explicitly Caching Data |
| 689 |
----------------------- |
| 690 |
|
| 691 |
Data can be cached explicitly by using the proxy methods like |
| 692 |
:meth:`Cache.set`, and :meth:`Cache.get` directly. There are many other proxy |
| 693 |
methods available via the :class:`Cache` class. |
| 694 |
|
| 695 |
For example: |
| 696 |
|
| 697 |
.. code-block:: python |
| 698 |
|
| 699 |
@app.route("/html") |
| 700 |
@app.route("/html/<foo>") |
| 701 |
def html(foo=None): |
| 702 |
if foo is not None: |
| 703 |
cache.set("foo", foo) |
| 704 |
bar = cache.get("foo") |
| 705 |
return render_template_string( |
| 706 |
"<html><body>foo cache: {{bar}}</body></html>", bar=bar |
| 707 |
) |
| 708 |
|
| 709 |
|
| 710 |
Subclassing ``Cache`` |
| 711 |
--------------------- |
| 712 |
|
| 713 |
The proxy methods are the extension's own entry point to the backend, so |
| 714 |
overriding them in a :class:`Cache` subclass also affects the caching done by |
| 715 |
:meth:`~Cache.cached` and :meth:`~Cache.memoize`. This makes it possible to add |
| 716 |
tracing, metrics or logging in one place and have it cover both explicit calls |
| 717 |
and the decorators: |
| 718 |
|
| 719 |
.. code-block:: python |
| 720 |
|
| 721 |
class InstrumentedCache(Cache): |
| 722 |
def get(self, *args, **kwargs): |
| 723 |
with tracer.trace("cache.get"): |
| 724 |
return super().get(*args, **kwargs) |
| 725 |
|
| 726 |
def set(self, *args, **kwargs): |
| 727 |
with tracer.trace("cache.set"): |
| 728 |
return super().set(*args, **kwargs) |
| 729 |
|
| 730 |
|
| 731 |
cache = InstrumentedCache(app, config={"CACHE_TYPE": "SimpleCache"}) |
| 732 |
|
| 733 |
Note that :meth:`~Cache.memoize` also uses :meth:`~Cache.get_many` and |
| 734 |
:meth:`~Cache.set_many` for its internal version keys, so an override will see |
| 735 |
that bookkeeping traffic as well. A cache miss makes two such round trips: one |
| 736 |
to read the version before building the key, and one after the entry is written |
| 737 |
to update the version keys expiry. |
| 738 |
|
| 739 |
To reach backend specific functionality that :class:`Cache` does not proxy, use |
| 740 |
the :attr:`Cache.cache` property instead of subclassing. |
| 741 |
|