0

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

8 Comments

i apologize, but i dont understand exactly how to use your suggestion. it may be obvious, but i am new to flask.
@alex: you'd use this in a separate view; one that you'd call to clear the cache for the cached view.
ok i see. so your solution is to use 'redirect' view in the middle? link on view1 -> redirect view (deletes cache)-> new view1
@alex: not really, if view1 is entirely cached for all possible route parameters, then that means it won't issue a redirect unless that was the cached response to begin with. How you steer your users to the cache clearing view is something you still have to work out.
@alex: I picked the code in this answer from a recent project where a backend API lets someone clear the cache if backend data has changed; this way the normal views are all heavily cached and highly performant, until the owners of the backend API send a signal that the data on which the view has been based has changed.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.