0
0
FlaskHow-ToBeginner · 4 min read

How to Use Redis Cache with Flask: Simple Guide

To use Redis cache with Flask, install the flask-redis package and configure Redis connection in your Flask app. Use the Redis client to set and get cached data easily within your routes or functions.
📐

Syntax

Here is the basic syntax to set up Redis cache in a Flask app:

  • from flask_redis import FlaskRedis: Import the Redis extension.
  • app.config['REDIS_URL']: Set the Redis server URL.
  • redis_client = FlaskRedis(app): Initialize Redis client with Flask app.
  • redis_client.set(key, value): Store data in cache.
  • redis_client.get(key): Retrieve data from cache.
python
from flask import Flask
from flask_redis import FlaskRedis

app = Flask(__name__)
app.config['REDIS_URL'] = "redis://localhost:6379/0"
redis_client = FlaskRedis(app)

@app.route('/cache')
def cache_example():
    redis_client.set('greeting', 'Hello, Redis!')
    message = redis_client.get('greeting')
    return message.decode('utf-8') if message else 'No cache found'  
💻

Example

This example shows a simple Flask app that caches a greeting message in Redis and retrieves it on a web request.

python
from flask import Flask
from flask_redis import FlaskRedis

app = Flask(__name__)
app.config['REDIS_URL'] = "redis://localhost:6379/0"
redis_client = FlaskRedis(app)

@app.route('/')
def index():
    # Set cache
    redis_client.set('welcome_msg', 'Welcome to Flask with Redis!')
    # Get cache
    cached_msg = redis_client.get('welcome_msg')
    if cached_msg:
        return cached_msg.decode('utf-8')
    return 'Cache is empty'

if __name__ == '__main__':
    app.run(debug=True)
Output
Welcome to Flask with Redis!
⚠️

Common Pitfalls

  • Not running a Redis server locally or on the configured URL causes connection errors.
  • Forgetting to decode bytes returned by redis_client.get() leads to unreadable output.
  • Using Redis commands outside Flask app context without proper initialization.
  • Not handling cache misses (null returns) can cause errors.
python
from flask import Flask
from flask_redis import FlaskRedis

app = Flask(__name__)
app.config['REDIS_URL'] = "redis://localhost:6379/0"
redis_client = FlaskRedis(app)

@app.route('/')
def index():
    # Wrong: Not decoding bytes
    cached_msg = redis_client.get('welcome_msg')
    return cached_msg  # This returns bytes, not string

# Correct way:
# cached_msg = redis_client.get('welcome_msg')
# if cached_msg:
#     return cached_msg.decode('utf-8')
# return 'Cache empty'
📊

Quick Reference

Here is a quick cheat-sheet for Redis cache commands in Flask:

CommandDescription
redis_client.set(key, value)Store a value in Redis cache with the given key.
redis_client.get(key)Retrieve the value for the given key (returns bytes).
redis_client.delete(key)Remove the key and its value from cache.
redis_client.exists(key)Check if a key exists in cache (returns 1 or 0).
redis_client.expire(key, seconds)Set expiration time for a key in seconds.

Key Takeaways

Install and configure flask-redis to connect Flask with Redis cache easily.
Always decode bytes returned by redis_client.get() before using the cached data.
Ensure Redis server is running and accessible at the configured URL.
Handle cache misses gracefully to avoid errors in your Flask app.
Use Redis commands like set, get, delete, and expire to manage cache effectively.