How to use caching in Flask

Published on Aug. 22, 2023, 12:15 p.m.

To use caching in Flask, you can use the Flask-Caching extension. Here is an example of how to do it:

  1. Install the Flask-Caching extension with pip:
pip install Flask-Caching
  1. Import and initialize the extension in your Flask application:
from flask import Flask
from flask_caching import Cache

app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
  1. Use the cache.cached() decorator to cache the output of a function:
@app.route('/')
@cache.cached(timeout=60)  # cache for 60 seconds
def index():
    # some expensive computation here...
    return 'Hello World!'

In this example, the index function will only be executed once every 60 seconds, and subsequent requests to the same URL will return the cached result. You can also use other cache types besides ‘simple’, such as ‘redis’ or ‘memcached’, by changing the CACHE_TYPE configuration parameter.

Note that caching can greatly improve the performance of your Flask application, but it should be used judiciously, as cached data may become stale or outdated.

here’s an example of how to use Flask-Caching in a Flask application:

from flask import Flask
from flask_caching import Cache

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

@app.route('/')
@cache.cached(timeout=60)  # cache for 60 seconds
def index():
    # some expensive computation here...
    return 'Hello, world!'

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

In this example, we create a Flask app and initialize a Cache instance with the 'simple' cache type. We then use the @cache.cached() decorator on the index function with a cache timeout of 60 seconds. This means that the result of the index function will be cached for 60 seconds, and subsequent requests to the same URL will return the cached result.

Note that there are other cache types available in Flask-Caching, such as 'filesystem', 'redis', and 'memcached'. You can customize the cache behavior by changing the configuration options passed to the Cache constructor.

Also note that caching can greatly improve the performance of your Flask application, but it should be used judiciously, as cached data may become stale or outdated.