0
0
Flaskframework~5 mins

Flask-Caching for response caching

Choose your learning style9 modes available
Introduction

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.

When your app shows data that doesn't change often, like a homepage or product list.
When you want to reduce the load on your server by not repeating heavy calculations.
When you want to speed up API responses for repeated requests.
When you want to improve user experience by making pages load faster.
When you want to save bandwidth by sending cached responses instead of generating new ones.
Syntax
Flask
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.

Examples
This caches the homepage response for 30 seconds.
Flask
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.'
This caches the current time for 10 seconds, so repeated requests within 10 seconds get the same time.
Flask
@app.route('/time')
@cache.cached(timeout=10)
def time():
    import datetime
    return f"Current time: {datetime.datetime.now()}"
This example uses filesystem caching to store cache on disk instead of memory.
Flask
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.'
Sample Program

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.

Flask
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)
OutputSuccess
Important Notes

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.

Summary

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.