Caching improves application performance by reducing redundant computations and database queries. Flask can integrate with caching systems like Redis or Memcached to store and retrieve data efficiently.
This article demonstrates step-by-step how to implement caching using Redis or Memcached in a Flask application.
Install Flask and a caching library like Flask-Caching
and either Redis or Memcached:
pip install flask flask-caching redis
If using Memcached, install the pymemcache
library:
pip install pymemcache
Install and start the caching service on your system:
sudo apt update sudo apt install redis sudo systemctl start redis
sudo apt update sudo apt install memcached sudo systemctl start memcached
Update your Flask application to include caching:
from flask import Flask from flask_caching import Cache app = Flask(__name__) # Configure caching app.config['CACHE_TYPE'] = 'RedisCache' # Use 'MemcachedCache' for Memcached app.config['CACHE_REDIS_HOST'] = 'localhost' app.config['CACHE_REDIS_PORT'] = 6379 cache = Cache(app)
Use the @cache.cached
decorator to cache specific routes:
@app.route('/') @cache.cached(timeout=60) def home(): import time time.sleep(2) # Simulate a slow computation return "Welcome to the cached Flask app!"
This caches the response for 60 seconds, reducing the computation time for repeated requests.
Manually store and retrieve data using the cache
object:
@app.route('/store') def store_data(): cache.set('key', 'value', timeout=300) # Cache for 5 minutes return "Data cached successfully!" @app.route('/retrieve') def retrieve_data(): value = cache.get('key') return f"Cached value: {value}"
Test your application to ensure caching works as expected. Use Redis or Memcached monitoring tools to confirm data storage.
redis-cli KEYS *
telnet localhost 11211 stats items
Clear the entire cache when needed:
cache.clear()
By integrating Redis or Memcached with Flask, you can significantly enhance the performance of your application by caching frequently accessed data. This reduces the load on your database and speeds up responses.