0
0
Flaskframework~5 mins

Response caching strategies in Flask

Choose your learning style9 modes available
Introduction

Response caching helps your web app send data faster by saving answers to repeat requests. This makes your app quicker and uses less work from the server.

When your app shows data that doesn't change often, like a blog post or product info.
When many users ask for the same page or data, like a homepage or popular article.
When you want to reduce server load during busy times.
When you want to improve user experience by loading pages faster.
When you want to save bandwidth by not sending the same data repeatedly.
Syntax
Flask
from flask_caching import Cache

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

@app.route('/data')
@cache.cached(timeout=60)
def data():
    # generate response
    return 'Hello, cached world!'

The @cache.cached(timeout=seconds) decorator saves the response for the given time.

You need to set up Cache with your Flask app before using caching decorators.

Examples
This caches the current time for 30 seconds, so repeated calls within 30 seconds return the same time.
Flask
from flask_caching import Cache

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

@app.route('/time')
@cache.cached(timeout=30)
def current_time():
    import datetime
    return str(datetime.datetime.now())
You can set a custom key prefix to control cache keys manually.
Flask
@cache.cached(timeout=120, key_prefix='my_key')
def my_view():
    return 'Cached with custom key prefix'
memoize caches function results based on arguments, useful for expensive computations.
Flask
@cache.memoize(timeout=50)
def expensive_function(param):
    # some slow calculation
    return param * 2
Sample Program

This Flask app shows the current time on the homepage. The time is cached for 10 seconds, so refreshing the page within 10 seconds shows the same time. After 10 seconds, it 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=10)
def home():
    now = datetime.datetime.now()
    return f'Current time is {now.strftime("%H:%M:%S")}'

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

Use caching carefully for data that changes often to avoid showing old info.

Simple cache stores data in memory, good for development or small apps.

For bigger apps, use Redis or Memcached for caching backend.

Summary

Response caching saves server work and speeds up your app.

Use @cache.cached to cache whole responses for a time.

Choose caching backend based on your app size and needs.