control flask-cache'ing from a view

810 Views Asked by At

I am wondering if there is a way to allow the user to control the caching properties of a given view using Flask-Cache.

For example, I would like for a view to be cached indefinitely unless the user clicks a reload link, in which case the view would be re-generated. I noticed there is an unless kwarg available to @cached decorator, but I am not sure how one would use this.

It seems that I should be able to add a url_for('this_view', dont_cache=True) somewhere on this_view's Jinja template.

1

There are 1 best solutions below

8
On BEST ANSWER

You can clear the cache; given a view function and the full path to the route, use:

from flask import current_app

with current_app.test_request_context(path=path):
    # the cache key can use `request` so we need to provide the correct
    # context here
    cache_key = view.make_cache_key()

cache.delete(cache_key)

Here path is the path to the view; you could use path = url_for('this_view') to generate it, and view is the (decorated) function object you used @cache.cached() on. cache is the Flask-Cache object.

Once the cache is cleared, a new request to that view will re-generate it.

If you never set a custom key_prefix (callable or string) then the default cache key for a given view is based on the request.path value; you could use this too:

cache_key = 'view/{}'.format(url_for('this_view'))
cache.delete(cache_key)

but the current_app.test_request_context / view.make_cache_key() dance above will make your cache key re-generation more robust.