Flask-Caching is an extension to Flask that adds caching support for various backends to any Flask application. By running on top of cachelib it supports all of werkzeug’s original caching backends through a uniformed API. It is also possible to develop your own caching backend by subclassing flask_caching.backends.base.BaseCache
class.
Version support
Since 1.8, Flask-Caching supports only Python 3.5+.
Installation
Install the extension with the following command:
pip install Flask-Caching
Set Up
Cache is managed through a Cache
instance:
from flask import Flask
from flask_caching import Cache
config = {
"DEBUG": True, # some Flask specific configs
"CACHE_TYPE": "SimpleCache", # Flask-Caching related configs
"CACHE_DEFAULT_TIMEOUT": 300
}
app = Flask(__name__)
# tell Flask to use the above defined config
app.config.from_mapping(config)
cache = Cache(app)
Caching View Functions
To cache view functions you will use the cached()
decorator. This decorator will use request.path by default for the cache_key:
@app.route("/")
@cache.cached(timeout=50)
def index():
return render_template('index.html')
The cached decorator has another optional argument called unless
. This argument accepts a callable that returns True or False. If unless
returns True
then it will bypass the caching mechanism entirely.
To dynamically determine the timeout within the view, you can return CachedResponse, a subclass of flask.Response:
@app.route("/")
@cache.cached()
def index():
return CachedResponse(
response=make_response(render_template('index.html')),
timeout=50,
)
Caching Pluggable View Classes
Flask’s pluggable view classes are also supported. To cache them, use the same cached()
decorator on the dispatch_request
method:
from flask.views import View
class MyView(View):
@cache.cached(timeout=50)
def dispatch_request(self):
return 'Cached for 50s'
Caching Other Functions
Using the same @cached
decorator you are able to cache the result of other non-view related functions. The only stipulation is that you replace the key_prefix
, otherwise it will use the request.path cache_key. Keys control what should be fetched from the cache. If, for example, a key does not exist in the cache, a new key-value entry will be created in the cache. Otherwise the the value (i.e. the cached result) of the key will be returned:
@cache.cached(timeout=50, key_prefix='all_comments')
def get_all_comments():
comments = do_serious_dbio()
return [x.author for x in comments]
cached_comments = get_all_comments()
Latest version