CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-flask-redis

A Flask extension that integrates Redis functionality into Flask applications through a simple and elegant interface

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

Flask-Redis

A Flask extension that integrates Redis functionality into Flask applications through a simple and elegant interface. Flask-Redis acts as a wrapper around the redis-py library, providing automatic Flask configuration management, support for custom Redis providers, and seamless integration with Flask's application factory pattern.

Package Information

  • Package Name: flask-redis
  • Language: Python
  • Installation: pip install flask-redis
  • Dependencies: Flask>=0.8, redis>=2.7.6
  • Python Support: Python 2.7, 3.5+

Core Imports

from flask_redis import FlaskRedis

Basic Usage

from flask import Flask
from flask_redis import FlaskRedis

# Method 1: Direct instantiation with app
app = Flask(__name__)
app.config['REDIS_URL'] = 'redis://localhost:6379/0'
redis_client = FlaskRedis(app)

# Method 2: Application factory pattern
redis_client = FlaskRedis()

def create_app():
    app = Flask(__name__)
    app.config['REDIS_URL'] = 'redis://localhost:6379/0'
    redis_client.init_app(app)
    return app

# Using Redis operations
@app.route('/')
def index():
    redis_client.set('key', 'value')
    return redis_client.get('key')

Capabilities

Flask Extension Class

The main FlaskRedis class that provides Redis integration for Flask applications.

class FlaskRedis:
    def __init__(self, app=None, strict=True, config_prefix='REDIS', **kwargs):
        """
        Initialize FlaskRedis extension.
        
        Parameters:
        - app: Flask application instance (optional)
        - strict: Use StrictRedis (True, default) or Redis (False) client. 
                  In modern redis-py versions, both point to the same Redis class.
        - config_prefix: Prefix for Flask configuration variables (default: 'REDIS')
        - **kwargs: Additional arguments passed to Redis client constructor
        """
    
    def init_app(self, app, **kwargs):
        """
        Initialize the extension with a Flask application.
        
        Parameters:
        - app: Flask application instance
        - **kwargs: Additional arguments for Redis client
        """
    
    @classmethod
    def from_custom_provider(cls, provider, app=None, **kwargs):
        """
        Create FlaskRedis instance with custom Redis provider.
        
        Parameters:
        - provider: Custom Redis client class (e.g., MockRedis)
        - app: Flask application instance (optional)
        - **kwargs: Additional arguments
        
        Returns:
        FlaskRedis instance configured with custom provider
        """
    
    def __getattr__(self, name):
        """
        Delegate attribute access to the underlying Redis client.
        
        Parameters:
        - name: Attribute name to access
        
        Returns:
        Value from the underlying Redis client
        """
    
    def __getitem__(self, name):
        """
        Delegate item access to the underlying Redis client.
        
        Parameters:
        - name: Key to access
        
        Returns:
        Value from Redis client using item access
        """
    
    def __setitem__(self, name, value):
        """
        Delegate item assignment to the underlying Redis client.
        
        Parameters:
        - name: Key to set
        - value: Value to assign
        """
    
    def __delitem__(self, name):
        """
        Delegate item deletion to the underlying Redis client.
        
        Parameters:
        - name: Key to delete
        """

Redis Client Access

Flask-Redis provides transparent access to all redis-py client methods through delegation. All methods from the redis-py library are available directly on the FlaskRedis instance.

# String operations
redis_client.set(name, value, ex=None, px=None, nx=False, xx=False)
redis_client.get(name)
redis_client.getset(name, value)
redis_client.incr(name, amount=1)
redis_client.decr(name, amount=1)

# Key operations  
redis_client.delete(*names)
redis_client.exists(*names)
redis_client.expire(name, time)
redis_client.ttl(name)
redis_client.keys(pattern='*')

# Hash operations
redis_client.hget(name, key)
redis_client.hset(name, key, value)
redis_client.hgetall(name)
redis_client.hdel(name, *keys)
redis_client.hkeys(name)

# List operations
redis_client.lpush(name, *values)
redis_client.rpush(name, *values)
redis_client.lpop(name)
redis_client.rpop(name)
redis_client.llen(name)
redis_client.lrange(name, start, end)

# Set operations
redis_client.sadd(name, *values)
redis_client.smembers(name)
redis_client.srem(name, *values)
redis_client.scard(name)

# Pub/Sub operations
redis_client.publish(channel, message)
redis_client.pubsub()

# Transaction operations
redis_client.pipeline()
redis_client.multi()
redis_client.exec()

# Magic methods also support item-style access
redis_client['key'] = 'value'  # Uses __setitem__
value = redis_client['key']    # Uses __getitem__
del redis_client['key']        # Uses __delitem__

Configuration

Flask-Redis uses Flask's configuration system with customizable prefixes.

# Default configuration key
REDIS_URL = 'redis://localhost:6379/0'

# With custom prefix
app.config['CUSTOM_PREFIX_URL'] = 'redis://localhost:6379/1'
redis_client = FlaskRedis(app, config_prefix='CUSTOM_PREFIX')

# Unix socket connections
REDIS_URL = 'unix://:password@/path/to/socket.sock?db=0'

Advanced Usage

Multiple Redis Instances

from flask import Flask
from flask_redis import FlaskRedis

app = Flask(__name__)
app.config['REDIS_URL'] = 'redis://localhost:6379/0'
app.config['CACHE_URL'] = 'redis://localhost:6379/1'

# Default instance
redis_store = FlaskRedis(app)

# Cache instance with custom prefix
redis_cache = FlaskRedis(app, config_prefix='CACHE')

Testing with MockRedis

from flask import Flask
from flask_redis import FlaskRedis
from mockredis import MockRedis

def create_app():
    app = Flask(__name__)
    
    if app.testing:
        redis_store = FlaskRedis.from_custom_provider(MockRedis)
    else:
        redis_store = FlaskRedis()
    
    redis_store.init_app(app)
    return app

Extension Integration

Flask-Redis automatically registers itself in Flask's extensions system using the lowercase version of the config prefix as the extension key:

# Access through app.extensions
app = Flask(__name__)
redis_client = FlaskRedis(app)

# The extension is available as app.extensions['redis'] (lowercase of 'REDIS' prefix)
assert app.extensions['redis'] is redis_client

# With custom prefix 'CACHE', extension key becomes 'cache'
redis_cache = FlaskRedis(app, config_prefix='CACHE')
assert app.extensions['cache'] is redis_cache

# Multiple instances with different prefixes
app.config['SESSION_URL'] = 'redis://localhost:6379/2'
session_store = FlaskRedis(app, config_prefix='SESSION')
assert app.extensions['session'] is session_store

Error Handling

Flask-Redis handles missing redis-py dependency gracefully when using custom providers:

# This works even if redis-py is not installed
redis_store = FlaskRedis.from_custom_provider(MockRedis, app)

# This will raise ImportError if redis-py is not installed
redis_store = FlaskRedis(app)  # Requires redis-py

The extension raises AssertionError if a None provider is passed to from_custom_provider():

# This will raise AssertionError
FlaskRedis.from_custom_provider(None, app)
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/flask-redis@0.4.x
Publish Source
CLI
Badge
tessl/pypi-flask-redis badge