How/where does Flask-Caching store data?

Wang Nick picture Wang Nick · May 31, 2017 · Viewed 7.5k times · Source

I just wonder how and where the response is stored when using Flask-Caching.

For example:

from flask import Flask, request
from flask_caching import Cache
import datetime

app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})

def make_cache_key(*args, **kwargs):
    return request.url

@app.route('/', methods=['GET'])
@cache.cached(timeout=50, key_prefix=make_cache_key)
def foo():
    time = str(datetime.datetime.now()) + " " + str(request.url)
    return time, 200

if __name__ == '__main__':   
    app.run(debug=True)

Answer

Josh Beam picture Josh Beam · May 31, 2017

tl;dr

In your example, it'll be stored in-memory of the Python interpreter.


Your setup is in-memory, so it won't scale between multiple servers. However, you have the option to specify a different cache backend (memcached or Redis, for example, or even your own custom one by extending the base cache class).

According to the docs we see that it uses werkzeug:

Besides providing support for all of werkzeug‘s supported caching backends through a uniformed API

Then when you look at the werkzeug cache docs:

If you are using the development server you can create a SimpleCache object, that one is a simple cache that keeps the item stored in the memory of the Python interpreter.

And then it goes on to show an example using your same setup ({'CACHE_TYPE': 'simple'}), which it says is in-memory of the Python interpreter.

If you wanna use a different cache backend, look at Configuring Flask Caching:

Built-in cache types:

null: NullCache (default)

simple: SimpleCache

memcached: MemcachedCache (pylibmc or memcache required)

gaememcached: GAEMemcachedCache

redis: RedisCache (Werkzeug 0.7 required)

filesystem: FileSystemCache

saslmemcached: SASLMemcachedCache (pylibmc required)