### Setup Cache with ConnectionFactoryProtocol Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/types.md Example of using ConnectionFactoryProtocol for type hinting when setting up a cache. ```python from django_redis.pool import ConnectionFactoryProtocol def setup_cache(factory: ConnectionFactoryProtocol) -> None: redis = factory.connect('redis://localhost:6379') ``` -------------------------------- ### Basic Redis Connection Example Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/connection-pool.md Demonstrates establishing a basic Redis connection using get_connection_factory, setting and getting a key, and disconnecting. ```python from django_redis.pool import get_connection_factory options = { 'USERNAME': 'default', 'PASSWORD': 'mypassword', 'SOCKET_TIMEOUT': 5.0, } factory = get_connection_factory(options) redis = factory.connect('redis://localhost:6379/0') # Use the connection redis.set('key', 'value') value = redis.get('key') # Clean up factory.disconnect(redis) ``` -------------------------------- ### ZlibCompressor Example Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/serializers-compressors.md Demonstrates how to use ZlibCompressor for Deflate compression. Built-in, no installation required. Options can be passed during initialization. ```python from django_redis.compressors.zlib import ZlibCompressor compressor = ZlibCompressor(options={ 'COMPRESSION_LEVEL': 6, # 1-9, default is 6 }) compressed = compressor.compress(b'large data') original = compressor.decompress(compressed) ``` -------------------------------- ### BrotliCompressor Example Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/serializers-compressors.md Illustrates the usage of BrotliCompressor for better compression ratios. Requires the 'brotli' library to be installed. ```python from django_redis.compressors.brotli import BrotliCompressor compressor = BrotliCompressor(options={ 'COMPRESSION_LEVEL': 11, # 0-11 }) ``` -------------------------------- ### LZ4Compressor Example Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/serializers-compressors.md Demonstrates LZ4 compression for high-speed operations. Install with 'pip install django-redis[lz4]'. Options include compression level and acceleration factor. ```python from django_redis.compressors.lz4 import Lz4Compressor compressor = Lz4Compressor(options={ 'COMPRESSION_LEVEL': 9, # 1-12, higher = more compression 'ACCELERATION_FACTOR': 1, }) ``` -------------------------------- ### ZstdCompressor Example Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/serializers-compressors.md Shows how to use Zstandard compression, a modern alternative to zlib. Requires 'pip install django-redis[pyzstd]'. Compression level is configurable. ```python from django_redis.compressors.zstd import ZstdCompressor compressor = ZstdCompressor(options={ 'COMPRESSION_LEVEL': 3, # 1-22 }) ``` -------------------------------- ### Start Redis and Sentinel with Docker Compose Source: https://github.com/jazzband/django-redis/blob/master/tests/README.rst Starts Redis and a Sentinel instance using the provided Docker Compose file. This command is essential for setting up the testing environment. ```bash # start redis and a sentinel (uses docker with image redis:alpine) docker compose -f tests/compose.yml up --detach --wait ``` -------------------------------- ### GzipCompressor Example Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/serializers-compressors.md Shows how to use GzipCompressor for Gzip compression. This is a built-in option. Compression level can be configured. ```python from django_redis.compressors.gzip import GzipCompressor compressor = GzipCompressor(options={ 'COMPRESSION_LEVEL': 6, }) compressed = compressor.compress(b'large data') ``` -------------------------------- ### Custom Client Implementation Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/README.md Example of creating a custom client by inheriting from DefaultClient and adding custom cache logic. ```python from django_redis.client.default import DefaultClient class CustomClient(DefaultClient): def custom_method(self): # Custom cache logic pass ``` -------------------------------- ### Install django-redis Source: https://github.com/jazzband/django-redis/blob/master/README.rst Install the django-redis package using pip. ```console $ python -m pip install django-redis ``` -------------------------------- ### Default Client Replication Setup Source: https://github.com/jazzband/django-redis/blob/master/README.rst Configure the DefaultClient to connect to a Redis replication setup by specifying primary and replica server URLs in the LOCATION list. ```python "LOCATION": [ "redis://127.0.0.1:6379/1", "redis://127.0.0.1:6378/1", ] ``` -------------------------------- ### Redis Configuration with Authentication Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/configuration.md Example of configuring a Redis instance with authentication and connection pool options. ```python CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'rediss://user:password@redis.example.com:6380/1', 'OPTIONS': { 'SOCKET_TIMEOUT': 5.0, 'SOCKET_CONNECT_TIMEOUT': 5.0, 'CONNECTION_POOL_KWARGS': {'max_connections': 50}, } } } ``` -------------------------------- ### Install django-redis with Optional Dependencies Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/README.md Install the core django-redis package. Optional dependencies can be installed for specific features like faster parsing, compression, or serialization formats. ```bash pip install django-redis # Optional dependencies for specific features pip install django-redis[hiredis] # Faster C-based parser pip install django-redis[lz4] # LZ4 compression pip install django-redis[msgpack] # MessagePack serialization pip install django-redis[pyzstd] # Zstandard compression ``` -------------------------------- ### IdentityCompressor Example Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/serializers-compressors.md Demonstrates the IdentityCompressor, which performs no actual compression. Use this when compression is not desired. ```python from django_redis.compressors.identity import IdentityCompressor compressor = IdentityCompressor(options={}) result = compressor.compress(b'test') # Returns b'test' unchanged ``` -------------------------------- ### get_connection_factory for Sentinel Setup Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/connection-pool.md Instantiates a SentinelConnectionFactory for Redis Sentinel setups, requiring SENTINELS and SENTINEL_SERVICE_NAME. ```python # Sentinel setup factory = get_connection_factory({ 'SENTINELS': [('sentinel1', 26379)], 'SENTINEL_SERVICE_NAME': 'mymaster', }) ``` -------------------------------- ### Mixed Sentinel and Default Client Configuration Source: https://github.com/jazzband/django-redis/blob/master/README.rst Example showing how to configure both Sentinel and Default clients within the same CACHES dictionary. ```python SENTINELS = [ ('sentinel-1', 26379), ('sentinel-2', 26379), ('sentinel-3', 26379), ] CACHES = { "sentinel": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://service_name/db", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.SentinelClient", "SENTINELS": SENTINELS, "CONNECTION_POOL_CLASS": "redis.sentinel.SentinelConnectionPool", "CONNECTION_FACTORY": "django_redis.pool.SentinelConnectionFactory", }, }, "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", }, }, } ``` -------------------------------- ### Install Hiredis for Performance Source: https://github.com/jazzband/django-redis/blob/master/README.rst Install the hiredis package using pip to enable faster C-based parsing for Redis replies. No additional Django configuration is needed. ```console $ python -m pip install hiredis ``` -------------------------------- ### Sentinel Configuration Example Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/connection-pool.md Shows how to configure a connection factory for Redis Sentinel with multiple sentinels, service name, and connection options for failover. ```python options = { 'SENTINELS': [ ('sentinel1.example.com', 26379), ('sentinel2.example.com', 26379), ('sentinel3.example.com', 26379), ], 'SENTINEL_SERVICE_NAME': 'mymaster', 'PASSWORD': 'mypassword', 'SOCKET_TIMEOUT': 5.0, 'SOCKET_CONNECT_TIMEOUT': 5.0, } factory = get_connection_factory(options) # Connection will automatically failover if master goes down redis = factory.connect('redis://localhost:6379/0') ``` -------------------------------- ### Example Usage of CacheKey Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/types.md Demonstrates how to create a CacheKey and extract the original key using the `original_key()` method. ```python from django_redis.util import CacheKey key: CacheKey = cache.client.make_key('user:123', version=1) original = key.original_key() # Returns 'user:123' ``` -------------------------------- ### PatternT: Key Matching Example Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/types.md Demonstrates using PatternT (glob pattern) for key scanning operations. ```python # Match any keys starting with 'user:' matching = cache.keys('user:*') # Match pattern with character class cache.delete_pattern('cache:v[12]:*') ``` -------------------------------- ### MsgPackSerializer Example Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/serializers-compressors.md Illustrates the usage of MsgPackSerializer for efficient binary serialization. It provides a compact format and is faster than pickle, with cross-language support. ```python from django_redis.serializers.msgpack import MsgPackSerializer serializer = MsgPackSerializer(options={}) data = serializer.dumps({'user': 'alice', 'id': 123}) original = serializer.loads(data) ``` -------------------------------- ### Basic Single Redis Instance Configuration Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/configuration.md Example of a basic Django settings configuration for a single Redis instance. ```python CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379/1', 'TIMEOUT': 300, 'KEY_PREFIX': 'myapp', 'VERSION': 1, } } ``` -------------------------------- ### Custom Cache Client Implementation Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/types.md Example of creating a custom cache client by subclassing DefaultClient and adding custom methods. ```python from typing import TYPE_CHECKING, Generic from django_redis.client.default import DefaultClient from django_redis.pool import RedisType, ConnectionPoolType, RedisParserType from django_redis.serializers.base import BaseSerializer from django_redis.compressors.base import BaseCompressor class CustomClient( DefaultClient[RedisType, ConnectionPoolType, RedisParserType, BaseSerializer, BaseCompressor] ): def custom_method(self) -> None: redis = self.get_client(write=True) redis.set('custom:key', 'value') ``` -------------------------------- ### ExpiryT: Numeric Timeout Example Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/types.md Shows how to set cache expiration using a numeric timeout in seconds. ```python # Numeric (seconds) cache.expire('key', 3600) ``` -------------------------------- ### Custom Compressor Implementation Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/README.md Example of creating a custom compressor by inheriting from BaseCompressor and implementing `compress` and `decompress` methods. ```python from django_redis.compressors.base import BaseCompressor class CustomCompressor(BaseCompressor): def compress(self, value): # Custom implementation return compressed_bytes def decompress(self, value): # Custom implementation return decompressed_bytes ``` -------------------------------- ### FieldT: Hash Operations Example Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/types.md Provides examples of using FieldT (string) for hash operations like hset and hdel. ```python cache.hset('user:123', 'name', 'Alice') # field='name' cache.hdel('user:123', 'email') # field='email' ``` -------------------------------- ### Connection Factory Usage Examples Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/SUMMARY.txt Demonstrates various ways to use the ConnectionFactory for establishing Redis connections. This includes basic usage, sentinel configurations, custom pools, and custom parsers. ```python # Basic usage factory = ConnectionFactory(hosts={0: 'redis://localhost:6379/0'}) connection = factory.get_connection(0) # Sentinel usage sentinel_factory = SentinelConnectionFactory(hosts=[('localhost', 26379)], sentinel_kwargs={'socket_timeout': 0.5}) connection = sentinel_factory.get_connection(0) # Custom pool usage custom_pool_factory = ConnectionFactory(pool_cls=ConnectionPool, pool_options={'max_connections': 10}) connection = custom_pool_factory.get_connection(0) # Custom parser usage class CustomParser: def parse_response(self, response, **options): return response custom_parser_factory = ConnectionFactory(parser_cls=CustomParser) connection = custom_parser_factory.get_connection(0) ``` -------------------------------- ### Enable Sentinel Connection Factory Source: https://github.com/jazzband/django-redis/blob/master/README.rst Configure django-redis to use the SentinelConnectionFactory for Redis Sentinel setups by setting DJANGO_REDIS_CONNECTION_FACTORY. ```python # Enable the alternate connection factory. DJANGO_REDIS_CONNECTION_FACTORY = 'django_redis.pool.SentinelConnectionFactory' # These sentinels are shared between all the examples, and are passed # directly to redis Sentinel. These can also be defined inline. SENTINELS = [ ('sentinel-1', 26379), ('sentinel-2', 26379), ('sentinel-3', 26379), ] CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", ``` -------------------------------- ### Django-Redis Compressor Tuning Recommendations Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/serializers-compressors.md Configuration examples for different performance tuning scenarios in Django-Redis. Choose based on latency, network I/O, or storage requirements. ```python # High-speed, low-latency: no compression COMPRESSOR = 'django_redis.compressors.identity.IdentityCompressor' ``` ```python # Network I/O bound: Lz4 (fast compression) COMPRESSOR = 'django_redis.compressors.lz4.Lz4Compressor' OPTIONS = {'COMPRESSION_LEVEL': 9} ``` ```python # Storage bound: Zstd or Brotli (better compression) COMPRESSOR = 'django_redis.compressors.zstd.ZstdCompressor' OPTIONS = {'COMPRESSION_LEVEL': 9} ``` ```python # Maximum compression: LZMA COMPRESSOR = 'django_redis.compressors.lzma.LzmaCompressor' ``` -------------------------------- ### get Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/default-client.md Retrieves a value from the cache. If the key is not found, a default value is returned. ```APIDOC ## get ### Description Retrieves a value from the cache. If the key is not found, a default value is returned. ### Method `get` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (str) - Required - Cache key - **default** (Any | None) - Optional - Value to return if key not found. Defaults to None. - **version** (int | None) - Optional - Version for key isolation. Defaults to None. - **client** (Redis | None) - Optional - Custom Redis client to use. Defaults to None. ### Request Example ```python user = client.get('user:100') user = client.get('user:999', default={}) ``` ### Response #### Success Response - **Any** - Deserialized value or default #### Response Example ```python {'id': 100, 'name': 'Alice'} ``` ``` -------------------------------- ### Custom Serializer Implementation Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/README.md Example of creating a custom serializer by inheriting from BaseSerializer and implementing `dumps` and `loads` methods. ```python from django_redis.serializers.base import BaseSerializer class CustomSerializer(BaseSerializer): def dumps(self, value): # Custom implementation return encoded_bytes def loads(self, value): # Custom implementation return decoded_value ``` -------------------------------- ### Primary/Replica Replication Configuration Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/configuration.md Example of configuring Django-redis for primary/replica replication, with an option to set replicas to read-only. ```python CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': ( 'redis://primary:6379/0,', 'redis://replica1:6379/0,', 'redis://replica2:6379/0' ), 'OPTIONS': { 'REPLICA_READ_ONLY': True, # Replicas read-only } } } ``` -------------------------------- ### ExpiryT: Timedelta Object Example Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/types.md Illustrates setting cache expiration with a Python timedelta object. ```python # Timedelta from datetime import timedelta cache.expire('key', timedelta(hours=1)) ``` -------------------------------- ### AbsExpiryT: Datetime Object Example Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/types.md Demonstrates using a Python datetime object for cache expiration. ```python # Datetime object cache.expire_at('key', datetime.now() + timedelta(hours=1)) ``` -------------------------------- ### AbsExpiryT: Unix Timestamp Example Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/types.md Demonstrates using an integer Unix timestamp for cache expiration. ```python import time from datetime import datetime # Integer timestamp cache.expire_at('key', int(time.time()) + 3600) ``` -------------------------------- ### Handle Django-Redis ImproperlyConfigured Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/errors.md Examples demonstrating Django-redis's ImproperlyConfigured exception due to missing or invalid cache configurations. ```python # Missing LOCATION CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', # Missing LOCATION - raises ImproperlyConfigured } } # Invalid SOCKET_TIMEOUT CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://localhost:6379/1', 'OPTIONS': { 'SOCKET_TIMEOUT': 'invalid', # Must be float/int } } } # Invalid CLIENT_CLASS CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://localhost:6379/1', 'OPTIONS': { 'CLIENT_CLASS': 'non.existent.Class', # Import fails } } } ``` -------------------------------- ### LZMACompressor Example Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/serializers-compressors.md Illustrates LZMA compression for achieving the maximum compression ratio. Available via the built-in lzma module (Python 3.3+). Options include format, compression level, and preset. ```python from django_redis.compressors.lzma import LzmaCompressor compressor = LzmaCompressor(options={ 'FORMAT': 'xz', # 'alone' or 'xz' 'COMPRESSION_LEVEL': 6, # 0-9 'PRESET': 6, # 0-9 }) ``` -------------------------------- ### Scan Set Members with Match Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/redis-cache.md Scans a set for members matching a glob pattern. This example retrieves all matching members at once. ```python # Get all at once members = cache.sscan('tags:popular', match='py*') ``` -------------------------------- ### PickleSerializer Example Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/serializers-compressors.md Demonstrates using PickleSerializer for serializing and deserializing Python objects. This is the default serializer and supports all Python types. ```python from django_redis.serializers.pickle import PickleSerializer serializer = PickleSerializer(options={}) data = serializer.dumps({'user': 'alice', 'id': 123}) original = serializer.loads(data) ``` -------------------------------- ### Basic Cache Operations Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/MODULE-INDEX.md Demonstrates fundamental cache operations like setting, getting, and deleting keys using Django's cache API. ```python from django.core.cache import cache # Basic operations cache.set('key', value) value = cache.get('key') cache.delete('key') ``` -------------------------------- ### Custom Key Reversal Function Implementation Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/configuration.md Example of a custom function to extract the original key from a versioned key by removing prefixes. ```python def my_reverse_key(key): """Extract original key from versioned key.""" # Remove version prefix and key prefix return key.split(':')[-1] ``` -------------------------------- ### Get Replica Redis Client Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/default-client.md Retrieves a raw Redis client instance for read operations from a replica. This is useful in replication setups to distribute read load. ```python # Get replica connection (for reads in replication setup) redis = client.get_client(write=False) ``` -------------------------------- ### Get Primary Redis Client Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/default-client.md Retrieves a raw Redis client instance for write operations. This method is used to obtain the primary connection in a replication setup. ```python # Get primary connection (for writes) redis = client.get_client(write=True) ``` -------------------------------- ### Django Cache Configuration with Compressor Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/serializers-compressors.md Example of configuring Django settings to use RedisCache with a specific compressor (ZlibCompressor in this case). Includes options for client class, serializer, parser, and connection pool. ```python CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379/1', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', 'SERIALIZER': 'django_redis.serializers.json.JSONSerializer', 'COMPRESSOR': 'django_redis.compressors.zlib.ZlibCompressor', 'PARSER_CLASS': 'redis.connection.HiredisParser', 'CONNECTION_POOL_KWARGS': { 'max_connections': 50, 'retry_on_timeout': True, }, 'COMPRESSION_LEVEL': 6, # For compressors that support it } } } ``` -------------------------------- ### zrevrange Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/sorted-sets.md Get members by index range in reverse order (highest score first). This method allows specifying a start and end index, and optionally including scores. ```APIDOC ## zrevrange ### Description Get members by index range in reverse order (high to low score). ### Method `zrevrange(self, key: str, start: int, end: int, withscores: bool = False, score_cast_func: type = float, version: int | None = None, client: Redis | None = None)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | key | str | — | Sorted set key name | | start | int | — | Start index (0-based, in reverse order) | | end | int | — | End index (inclusive) | | withscores | bool | False | Include scores | | score_cast_func | type | float | Function to cast scores | | version | int | None | Version for key isolation | | client | Redis | None | Custom Redis client | ### Return Type `list[Any] | list[tuple[Any, float]]` ### Examples ```python # Get top 3 members (highest scores) top3 = client.zrevrange('leaderboard', 0, 2) # With scores top3_with_scores = client.zrevrange('leaderboard', 0, 2, withscores=True) # Get all in reverse order all_reversed = client.zrevrange('leaderboard', 0, -1, withscores=True) ``` ``` -------------------------------- ### Configure Production with Multiple Cache Types Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/configuration.md This example demonstrates setting up multiple distinct cache configurations for production use, including default, sessions, and lock caches. It also configures Django's session engine to use the cache. ```python CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://cache:6379/0', 'TIMEOUT': 300, }, 'sessions': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://cache:6379/1', 'TIMEOUT': None, # Session timeout controlled by Django 'KEY_PREFIX': 'sessions', }, 'lock': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://cache:6379/2', 'TIMEOUT': 60, 'KEY_PREFIX': 'lock', } } SESSION_ENGINE = 'django.contrib.sessions.backends.cache' SESSION_CACHE_ALIAS = 'sessions' ``` -------------------------------- ### Lz4Compressor Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/serializers-compressors.md LZ4 compression for high-speed compression/decompression. Requires installation via `pip install django-redis[lz4]`. ```APIDOC ## Lz4Compressor LZ4 compression for high-speed compression/decompression. **Class:** `django_redis.compressors.lz4.Lz4Compressor` **Installation:** `pip install django-redis[lz4]` ```python from django_redis.compressors.lz4 import Lz4Compressor compressor = Lz4Compressor(options={ 'COMPRESSION_LEVEL': 9, # 1-12, higher = more compression 'ACCELERATION_FACTOR': 1, }) ``` **Configuration Keys:** - `COMPRESSION_LEVEL`: 1-12 (default: 0 = auto) - `ACCELERATION_FACTOR`: Trade speed for compression ratio **Pros:** Very fast compression/decompression **Cons:** Lower compression ratio than zlib ``` -------------------------------- ### Initialize ConnectionFactory with Options Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/connection-pool.md Instantiate a ConnectionFactory with a dictionary of configuration options. This includes specifying custom connection pool and client classes, as well as connection-specific parameters like timeouts and passwords. ```python options = { 'CONNECTION_POOL_CLASS': 'redis.connection.ConnectionPool', 'CONNECTION_POOL_KWARGS': {'max_connections': 50}, 'REDIS_CLIENT_CLASS': 'redis.client.Redis', 'REDIS_CLIENT_KWARGS': {}, 'SOCKET_TIMEOUT': 5.0, 'SOCKET_CONNECT_TIMEOUT': 5.0, 'PASSWORD': 'secret', } factory = ConnectionFactory(options) ``` -------------------------------- ### ZstdCompressor Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/serializers-compressors.md Zstandard compression, a modern alternative to zlib. Requires installation via `pip install django-redis[pyzstd]`. ```APIDOC ## ZstdCompressor Zstandard compression (modern alternative to zlib). **Class:** `django_redis.compressors.zstd.ZstdCompressor` **Installation:** `pip install django-redis[pyzstd]` ```python from django_redis.compressors.zstd import ZstdCompressor compressor = ZstdCompressor(options={ 'COMPRESSION_LEVEL': 3, # 1-22 }) ``` **Configuration Keys:** - `COMPRESSION_LEVEL`: 1-22 (default: 3) **Pros:** Better compression than zlib, faster decompression **Cons:** Requires external dependency ``` -------------------------------- ### Import RedisCache and cache Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/MODULE-INDEX.md Import the RedisCache class and the generic cache object from Django's cache framework. This is a common starting point for using Django-Redis as a cache backend. ```python from django.core.cache import cache from django_redis.cache import RedisCache ``` -------------------------------- ### Get Redis Client using Pre-formatted Parameters Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/connection-pool.md Retrieve a Redis client instance using a pre-formatted dictionary of connection parameters. This method leverages a cached connection pool for efficiency. ```python params = factory.make_connection_params('redis://localhost:6379/0') redis = factory.get_connection(params) ``` -------------------------------- ### zcard Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/sorted-sets.md Get the number of members in a sorted set. ```APIDOC ## zcard ### Description Get the number of members in a sorted set. ### Method `zcard` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **key** (str) - Required - Sorted set key name - **version** (int | None) - Optional - Version for key isolation - **client** (Redis | None) - Optional - Custom Redis client ### Return type `int` - cardinality (0 if key doesn't exist) ### Examples ```python count = client.zcard('leaderboard') ``` ``` -------------------------------- ### Constructor Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/default-client.md Initializes the DefaultClient with server details, parameters, and the parent cache backend. It supports various configuration options for serialization, compression, and connection handling. ```APIDOC ## Constructor ### Description Initializes the DefaultClient with server details, parameters, and the parent cache backend. It supports various configuration options for serialization, compression, and connection handling. ### Signature ```python def __init__(self, server: str | list[str], params: dict[str, Any], backend: BaseCache) -> None ``` ### Parameters #### Path Parameters - **server** (str | list[str]) - Required - Single Redis URL or comma-separated list of URLs for replication - **params** (dict[str, Any]) - Required - Cache configuration dict with OPTIONS, TIMEOUT, KEY_PREFIX, VERSION - **backend** (BaseCache) - Required - Parent cache backend instance ### Configuration Keys in params: - `OPTIONS`: dict with optional settings (see Configuration section) - `REVERSE_KEY_FUNCTION`: custom function to extract original key from versioned key - `TIMEOUT`: default cache timeout in seconds ### Supported OPTIONS: - `SERIALIZER`: path to serializer class (default: `django_redis.serializers.pickle.PickleSerializer`) - `COMPRESSOR`: path to compressor class (default: `django_redis.compressors.identity.IdentityCompressor`) - `CONNECTION_FACTORY`: path to connection factory (default: `django_redis.pool.ConnectionFactory`) - `REPLICA_READ_ONLY`: bool - only read from replicas (default: True) - `CLOSE_CONNECTION`: bool - close connection after each operation (default: False) ``` -------------------------------- ### BrotliCompressor Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/serializers-compressors.md Brotli compression for better compression ratios. Requires the 'brotli' library to be installed. ```APIDOC ## BrotliCompressor Brotli compression for better compression ratios. **Class:** `django_redis.compressors.brotli.BrotliCompressor` **Installation:** Available via optional dependency (requires brotli library) ```python from django_redis.compressors.brotli import BrotliCompressor compressor = BrotliCompressor(options={ 'COMPRESSION_LEVEL': 11, # 0-11 }) ``` **Configuration Keys:** - `COMPRESSION_LEVEL`: 0-11 (default: 11) **Pros:** Excellent compression ratio, modern **Cons:** Requires external dependency, slower compression ``` -------------------------------- ### Custom Client, Serializer, and Compressor Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/MODULE-INDEX.md Illustrates how to subclass the default client, serializer, and compressor for custom functionality. ```python from django_redis.client.default import DefaultClient from django_redis.serializers.base import BaseSerializer from django_redis.compressors.base import BaseCompressor class MyClient(DefaultClient): def custom_method(self): pass class MySerializer(BaseSerializer): def dumps(self, value): pass def loads(self, value): pass class MyCompressor(BaseCompressor): def compress(self, value): pass def decompress(self, value): pass ``` -------------------------------- ### Get All Set Members Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/redis-cache.md Use `smembers` to retrieve all members belonging to a specified set. ```python tags = cache.smembers('tags:popular') ``` -------------------------------- ### Sentinel Client Configuration with Options Source: https://github.com/jazzband/django-redis/blob/master/README.rst Configure the SentinelClient with detailed options including client class, sentinels list, sentinel kwargs, and connection pool class. ```python "LOCATION": "redis://service_name/db", "OPTIONS": { # While the default client will work, this will check you # have configured things correctly, and also create a # primary and replica pool for the service specified by # LOCATION rather than requiring two URLs. "CLIENT_CLASS": "django_redis.client.SentinelClient", # Sentinels which are passed directly to redis Sentinel. "SENTINELS": SENTINELS, # kwargs for redis Sentinel (optional). Example with auth on sentinels "SENTINEL_KWARGS": { "username": "sentinel-user", "password": "sentinel-pass", }, # You can still override the connection pool (optional). "CONNECTION_POOL_CLASS": "redis.sentinel.SentinelConnectionPool", }, }, ``` -------------------------------- ### Get Set Cardinality Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/redis-cache.md Use `scard` to retrieve the number of members currently in a set. ```python size = cache.scard('tags:popular') ``` -------------------------------- ### Configure Compressor Options Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/configuration.md Select a compressor to reduce stored data size. Options range from no compression to various algorithms like zlib, gzip, lz4, zstd, brotli, and lzma. ```python 'OPTIONS': { # No compression (fastest) 'COMPRESSOR': 'django_redis.compressors.identity.IdentityCompressor', # Deflate compression 'COMPRESSOR': 'django_redis.compressors.zlib.ZlibCompressor', # Gzip compression 'COMPRESSOR': 'django_redis.compressors.gzip.GzipCompressor', # LZ4 (fast compression/decompression) 'COMPRESSOR': 'django_redis.compressors.lz4.Lz4Compressor', # Zstandard (modern, good compression) 'COMPRESSOR': 'django_redis.compressors.zstd.ZstdCompressor', # Brotli (best compression, slow) 'COMPRESSOR': 'django_redis.compressors.brotli.BrotliCompressor', # LZMA (maximum compression, very slow) 'COMPRESSOR': 'django_redis.compressors.lzma.LzmaCompressor', # Custom 'COMPRESSOR': 'myapp.compression.MyCompressor', } ``` -------------------------------- ### Custom Client Selection Logic Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/default-client.md Demonstrates how to subclass DefaultClient to implement custom logic for selecting the next Redis connection index. This allows for advanced load balancing strategies. ```python class CustomClient(DefaultClient): def get_next_client_index(self, write=True, tried=None): if tried is None: tried = [] # Custom load balancing logic here return super().get_next_client_index(write, tried) ``` -------------------------------- ### String Representation of ConnectionInterrupted Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/errors.md Provides an example of the string representation of a ConnectionInterrupted exception, showing the error message. ```python >>> e = ConnectionInterrupted(redis_client) >>> str(e) 'Redis ConnectionError: Connection refused' ``` -------------------------------- ### keys Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/redis-cache.md Get all cache keys matching a glob pattern. Warning: use `iter_keys` for large keysets. ```APIDOC ## keys ### Description Get all cache keys matching a glob pattern. Warning: use `iter_keys` for large keysets. ### Method `keys` ### Parameters #### Path Parameters - **pattern** (str) - Required - Glob pattern (supports *, ?, []) - **version** (int | None) - Optional - Cache version ### Return type `list[str]` - matching keys ### Example ```python session_keys = cache.keys('session:*') ``` ``` -------------------------------- ### Configure Client Class Options Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/configuration.md The OPTIONS dictionary allows specifying advanced client configurations. CLIENT_CLASS determines the client implementation, such as DefaultClient, HerdClient, SentinelClient, or ShardClient. ```python 'OPTIONS': { # Default client (handles everything) 'CLIENT_CLASS': 'django_redis.client.DefaultClient', # Herd protection (prevents thundering herd on cache miss) 'CLIENT_CLASS': 'django_redis.client.HerdClient', # Sentinel (automatic failover) 'CLIENT_CLASS': 'django_redis.client.SentinelClient', # Sharded (consistent hashing across multiple Redis instances) 'CLIENT_CLASS': 'django_redis.client.ShardClient', # Custom subclass 'CLIENT_CLASS': 'myapp.cache.MyCustomClient', } ``` -------------------------------- ### GzipCompressor Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/serializers-compressors.md Gzip compression using Python's gzip module. This is a built-in compressor and requires no additional installation. ```APIDOC ## GzipCompressor Gzip compression using Python's gzip module. **Class:** `django_redis.compressors.gzip.GzipCompressor` **Built-in, no installation required.** ```python from django_redis.compressors.gzip import GzipCompressor compressor = GzipCompressor(options={ 'COMPRESSION_LEVEL': 6, }) compressed = compressor.compress(b'large data') ``` **Configuration Keys:** - `COMPRESSION_LEVEL`: 1-9 (default: 6) **Pros:** Widely compatible, standard format **Cons:** Similar performance to zlib ``` -------------------------------- ### ZlibCompressor Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/serializers-compressors.md Deflate compression using Python's zlib module. This is a built-in compressor and requires no additional installation. ```APIDOC ## ZlibCompressor Deflate compression using Python's zlib module. **Class:** `django_redis.compressors.zlib.ZlibCompressor` **Built-in, no installation required.** ```python from django_redis.compressors.zlib import ZlibCompressor compressor = ZlibCompressor(options={ 'COMPRESSION_LEVEL': 6, # 1-9, default is 6 }) compressed = compressor.compress(b'large data') original = compressor.decompress(compressed) ``` **Configuration Keys:** - `COMPRESSION_LEVEL`: Compression level 1-9 (default: 6) - 1 = fastest, lowest compression - 9 = slowest, highest compression - 6 = good balance **Pros:** Built-in Python support, decent compression **Cons:** Slower than some alternatives ``` -------------------------------- ### Custom Parser Configuration Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/connection-pool.md Sets up a connection factory to use a specific parser class, such as the faster HiredisParser. ```python options = { 'PARSER_CLASS': 'redis.connection.HiredisParser', # Faster C parser } factory = get_connection_factory(options) ``` -------------------------------- ### Basic and Advanced Cache Operations Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/README.md Demonstrates common cache operations like setting, getting, and deleting keys, as well as advanced features like incrementing counters, using locks, and accessing the raw Redis client. ```python from django.core.cache import cache # Basic operations cache.set('user:123', {'name': 'Alice'}, timeout=3600) user = cache.get('user:123') cache.delete('user:123') # Advanced operations cache.incr('page_views') with cache.lock('critical_section'): # Critical code here pass # Raw Redis access from django_redis import get_redis_connection redis = get_redis_connection() redis.execute_command('CUSTOM_COMMAND') ``` -------------------------------- ### Configure Serializer Options Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/configuration.md Choose a serializer for encoding/decoding cache values. Options include Pickle, JSON, MessagePack, or a custom serializer. ```python 'OPTIONS': { # Pickle (supports all Python types) 'SERIALIZER': 'django_redis.serializers.pickle.PickleSerializer', # JSON (smaller, language-agnostic, limited types) 'SERIALIZER': 'django_redis.serializers.json.JSONSerializer', # MessagePack (compact, fast) 'SERIALIZER': 'django_redis.serializers.msgpack.MsgPackSerializer', # Custom 'SERIALIZER': 'myapp.serializers.MySerializer', } ``` -------------------------------- ### Configure Redis Client Keyword Arguments Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/configuration.md Specify additional arguments for Redis client initialization, such as encoding and decode_responses. ```python 'OPTIONS': { 'REDIS_CLIENT_KWARGS': { 'encoding': 'utf-8', 'decode_responses': False, } } ``` -------------------------------- ### Configure Cache with Username and Password in OPTIONS Source: https://github.com/jazzband/django-redis/blob/master/README.rst Configure Django to use django-redis with username and password authentication specified in the OPTIONS dictionary. ```python CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://localhost:6379/0", "OPTIONS": { "USERNAME": "django", "PASSWORD": "mysecret", } } } ``` -------------------------------- ### DefaultClient Constructor Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/default-client.md Initializes the DefaultClient with server details, parameters, and the parent cache backend instance. The params dictionary can include options like SERIALIZER, COMPRESSOR, and TIMEOUT. ```python def __init__(self, server: str | list[str], params: dict[str, Any], backend: BaseCache) -> None ``` -------------------------------- ### pttl Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/default-client.md Get remaining time-to-live for a key in milliseconds. This method allows checking the expiration time of a cached key. ```APIDOC ## pttl ### Description Get remaining time-to-live for a key in milliseconds. ### Method pttl ### Parameters #### Path Parameters - **key** (str) - Required - Cache key - **version** (int | None) - Optional - Version for key isolation - **client** (Redis | None) - Optional - Custom Redis client to use ### Return type `int | None` - milliseconds remaining ### Example ```python ms_remaining = client.pttl('rate_limit:user:123') ``` ``` -------------------------------- ### Enable Gzip Compression Source: https://github.com/jazzband/django-redis/blob/master/README.rst Activate gzip compression for cache values by specifying the GzipCompressor backend. ```python import gzip CACHES = { "default": { # ... "OPTIONS": { "COMPRESSOR": "django_redis.compressors.gzip.GzipCompressor", } } } ``` -------------------------------- ### Get value from cache Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/default-client.md Retrieves a value from the cache using its key. Returns a default value if the key is not found. ```python user = client.get('user:100') user = client.get('user:999', default={}) ``` -------------------------------- ### Enable Zlib Compression Source: https://github.com/jazzband/django-redis/blob/master/README.rst Activate zlib compression for cache values by specifying the ZlibCompressor backend. ```python CACHES = { "default": { # ... "OPTIONS": { "COMPRESSOR": "django_redis.compressors.zlib.ZlibCompressor", } } } ``` -------------------------------- ### Minimal Sentinel Client Configuration Source: https://github.com/jazzband/django-redis/blob/master/README.rst A minimal configuration for the SentinelClient, specifying the backend, location, client class, and sentinels. ```python "minimal": { "BACKEND": "django_redis.cache.RedisCache", # The SentinelClient will use this location for both the primaries # and replicas. "LOCATION": "redis://minimal_service_name/db", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.SentinelClient", "SENTINELS": SENTINELS, }, }, ``` -------------------------------- ### Configure Redis Client Class Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/configuration.md Choose the Redis client class to use. Options include the default 'redis.client.Redis' or 'redis.client.StrictRedis' for older redis-py versions. ```python 'OPTIONS': { 'REDIS_CLIENT_CLASS': 'redis.client.Redis', 'REDIS_CLIENT_CLASS': 'redis.client.StrictRedis', # Older redis-py } ``` -------------------------------- ### Configure Connection Pool Keyword Arguments Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/configuration.md Provide additional arguments for connection pool initialization, such as max_connections, retry_on_timeout, and socket_keepalive settings. ```python 'OPTIONS': { 'CONNECTION_POOL_KWARGS': { 'max_connections': 50, # Pool size 'retry_on_timeout': True, # Retry on timeouts 'socket_keepalive': True, # Keep-alive 'socket_keepalive_options': { 1: 1, # TCP_KEEPIDLE }, } } ``` -------------------------------- ### Type-Safe Cache Usage with Error Handling Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/types.md Example of type-safe cache usage with explicit error handling for ConnectionInterrupted exceptions. ```python from django.core.cache import cache from django_redis.exceptions import ConnectionInterrupted from typing import Optional def get_user_cached(user_id: int) -> Optional[dict]: """Get user from cache with error handling.""" try: return cache.get(f'user:{user_id}') except ConnectionInterrupted as e: # Handle connection error return None ``` -------------------------------- ### Configure Development with Local Unix Socket Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/configuration.md This configuration is suitable for local development environments using a Unix domain socket. It includes an option to ignore exceptions, making development more lenient. ```python CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'unix:///tmp/redis.sock?db=0', 'OPTIONS': { 'IGNORE_EXCEPTIONS': True, # Lenient in dev } } } ``` -------------------------------- ### Handling ConnectionInterrupted Exception Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/types.md Provides an example of how to catch and handle `ConnectionInterrupted` exceptions during cache operations, allowing for fallback logic. ```python from django_redis.exceptions import ConnectionInterrupted try: cache.set('key', 'value') except ConnectionInterrupted as e: print(f"Redis error: {e.__cause__}") # Fallback logic ``` -------------------------------- ### Shard Client Configuration Source: https://github.com/jazzband/django-redis/blob/master/README.rst Configure the ShardClient for distributed caching. Note that this client is experimental. ```python { "LOCATION": [ "redis://127.0.0.1:6379/1", "redis://127.0.0.1:6379/2", ], "OPTIONS": { "CLIENT_CLASS": "django_redis.client.ShardClient", } } ``` -------------------------------- ### RedisCache Constructor Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/redis-cache.md Initializes the RedisCache backend. It requires a Redis server connection string and a dictionary of parameters for configuration. ```APIDOC ## RedisCache Constructor ### Description Initializes the RedisCache backend. It requires a Redis server connection string and a dictionary of parameters for configuration. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Details - **server** (str) - Required - Redis connection URL or comma-separated list of URLs for replication. Supports `redis://`, `rediss://`, and `unix://` schemes. - **params** (dict[str, Any]) - Required - Configuration parameters including `OPTIONS`, `TIMEOUT`, `KEY_PREFIX`, `VERSION`. **params dictionary structure:** - `OPTIONS`: dict with backend-specific settings - `TIMEOUT`: Default cache timeout in seconds (can be `None` for infinite) - `KEY_PREFIX`: Prefix for all cache keys - `VERSION`: Cache version for key namespacing **OPTIONS keys:** - `CLIENT_CLASS`: Full path to client class (default: `django_redis.client.DefaultClient`) - `IGNORE_EXCEPTIONS`: bool - whether to catch Redis errors and return defaults (default: False) - `SERIALIZER`: Full path to serializer class (default: `django_redis.serializers.pickle.PickleSerializer`) - `COMPRESSOR`: Full path to compressor class (default: `django_redis.compressors.identity.IdentityCompressor`) - `CONNECTION_FACTORY`: Full path to connection factory (default: `django_redis.pool.ConnectionFactory`) - `REPLICA_READ_ONLY`: bool - only read from replicas (default: True) - `CLOSE_CONNECTION`: bool - close connection after each operation (default: False) ``` -------------------------------- ### Get Time-To-Live (TTL) in Milliseconds Source: https://github.com/jazzband/django-redis/blob/master/README.rst Retrieves the remaining time-to-live for a cache key in milliseconds. Returns 0 if the key does not exist. ```pycon >>> from django.core.cache import cache >>> cache.set("foo", "value", timeout=25) >>> cache.pttl("foo") 25000 >>> cache.pttl("not-existent") 0 ``` -------------------------------- ### Configure Default Cache Backend Source: https://github.com/jazzband/django-redis/blob/master/README.rst Configure Django to use django-redis as the default cache backend using a basic Redis URL. ```python CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", } } ``` -------------------------------- ### Get Time-To-Live (TTL) in Seconds Source: https://github.com/jazzband/django-redis/blob/master/README.rst Retrieves the remaining time-to-live for a cache key in seconds. Returns 0 if the key does not exist. ```pycon >>> from django.core.cache import cache >>> cache.set("foo", "value", timeout=25) >>> cache.ttl("foo") 25 >>> cache.ttl("not-existent") 0 ``` -------------------------------- ### Connect to Replica Redis Server Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/default-client.md Establishes and returns a new Redis connection to a replica server (index 1). ```python replica = client.connect(1) ``` -------------------------------- ### Configure Session Backend Source: https://github.com/jazzband/django-redis/blob/master/README.rst Configure Django to use django-redis as the session backend by setting the SESSION_ENGINE and SESSION_CACHE_ALIAS. ```python SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "default" ``` -------------------------------- ### Get Union of Sets Source: https://github.com/jazzband/django-redis/blob/master/_autodocs/api-reference/redis-cache.md Retrieves the union of multiple sets. Use this to combine elements from several sets into a single result set. ```python all_tags = cache.sunion('tags:popular', 'tags:trending', 'tags:new') ```