Flask-Caching helps your web app remember responses so it can send them faster next time. This saves time and makes your app feel quicker.
Flask-Caching for response caching
from flask_caching import Cache cache = Cache(app, config={'CACHE_TYPE': 'simple'}) @app.route('/some') @cache.cached(timeout=60) def some_view(): # generate response return 'Hello, cached!'
Use @cache.cached(timeout=seconds) above a view function to cache its response.
Configure cache type in Cache(app, config={...}). 'simple' stores cache in memory.
from flask_caching import Cache cache = Cache(app, config={'CACHE_TYPE': 'simple'}) @app.route('/') @cache.cached(timeout=30) def home(): return 'Welcome! This page is cached for 30 seconds.'
@app.route('/time') @cache.cached(timeout=10) def time(): import datetime return f"Current time: {datetime.datetime.now()}"
cache = Cache(app, config={'CACHE_TYPE': 'filesystem', 'CACHE_DIR': '/tmp/cache'})
@app.route('/data')
@cache.cached(timeout=120)
def data():
return 'Data cached on disk for 2 minutes.'This Flask app shows the current time on the homepage. The response is cached for 15 seconds, so refreshing the page within 15 seconds shows the same time. After 15 seconds, the cache expires and the time updates.
from flask import Flask from flask_caching import Cache import datetime app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) @app.route('/') @cache.cached(timeout=15) def index(): now = datetime.datetime.now() return f"Hello! Current time is {now.strftime('%H:%M:%S')}" if __name__ == '__main__': app.run(debug=True)
Cached responses are stored for the time you set in timeout. After that, the cache refreshes.
Use simple cache for development. For production, consider Redis or Memcached for better performance.
Remember to install Flask-Caching with pip install Flask-Caching before using it.
Flask-Caching stores responses to speed up your app.
Use @cache.cached(timeout=seconds) to cache view outputs.
Choose cache type based on your needs: simple, filesystem, Redis, etc.