Flask-Redis Integration

0.4.0 · maintenance · verified Thu Apr 16

Flask-Redis is a Flask extension that provides a convenient way to integrate Redis into your Flask applications. It abstracts away the direct management of Redis connections, allowing you to easily access a Redis client instance configured through your Flask app's configuration. The current version is 0.4.0, with the last release in 2019, indicating a maintenance-only or stable state.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize Flask-Redis with your Flask application and use the Redis client. It sets the Redis URL via application configuration, which can be overridden by an environment variable. The Redis client instance is then directly available for use, typically within request contexts or blueprints.

import os
from flask import Flask
from flask_redis import FlaskRedis

app = Flask(__name__)

# Configure Redis URL from environment variable or default
app.config['REDIS_URL'] = os.environ.get('REDIS_URL', 'redis://localhost:6379/0')

# Initialize Flask-Redis with the app
redis_client = FlaskRedis(app)

@app.route('/')
def index():
    try:
        redis_client.set('mykey', 'hello from flask-redis!')
        value = redis_client.get('mykey')
        if value:
            return f"Value from Redis: {value.decode()}"
        return "No value found in Redis."
    except Exception as e:
        return f"Error connecting to Redis: {e}"

if __name__ == '__main__':
    # Make sure a Redis server is running or set REDIS_URL environment variable
    print(f"Redis URL: {app.config['REDIS_URL']}")
    app.run(debug=True)

view raw JSON →