Redis built into a python package
—
Monkey-patch functionality to replace redis-py classes with redislite classes, enabling existing code to use embedded Redis servers without modification.
Patch all Redis classes provided by redislite to enable seamless replacement of redis-py.
def patch_redis(dbfile=None):
"""
Patch all the redis classes provided by redislite that have been patched.
Parameters:
dbfile (str, optional): The name of the Redis db file to be used. If
provided, all instances of redis.Redis() will share
a single instance of the embedded redis server.
Returns:
None
"""
def unpatch_redis():
"""
Unpatch all the redis classes provided by redislite that have been patched.
Returns:
None
"""Usage Examples:
import redislite.patch
# Patch all Redis classes to use redislite
redislite.patch.patch_redis('/tmp/shared.db')
# Now regular redis imports use redislite
import redis
r = redis.Redis() # Actually creates redislite.Redis instance
r.set('key', 'value')
# Restore original redis classes
redislite.patch.unpatch_redis()Patch the redis.Redis class specifically with redislite functionality.
def patch_redis_Redis(dbfile=None):
"""
Patch the redis module to replace the redis.Redis() class with the
redislite enhanced redislite.Redis() class that uses the embedded redis server.
Parameters:
dbfile (str, optional): The name of the Redis db file to be used. If this
argument is passed all instances of the redis.Redis
class will share a single embedded redis server.
Returns:
None
"""
def unpatch_redis_Redis():
"""
Unpatch the redis.Redis() class of the redis module and restore the
original redis.Redis() class.
Returns:
None
"""Usage Examples:
import redislite.patch
# Patch only Redis class
redislite.patch.patch_redis_Redis('/tmp/redis.db')
import redis
r = redis.Redis() # Uses redislite.Redis with embedded server
r.set('patched', 'true')
# Check if patching is active
from redislite.patch import Redis_Patched
print(f"Redis patched: {Redis_Patched}") # True
# Restore original Redis class
redislite.patch.unpatch_redis_Redis()
print(f"Redis patched: {Redis_Patched}") # FalsePatch the redis.StrictRedis class specifically with redislite functionality.
def patch_redis_StrictRedis(dbfile=None):
"""
Patch the redis module to replace the redis.StrictRedis() class with the
redislite enhanced redislite.StrictRedis() class that uses the embedded redis server.
Parameters:
dbfile (str, optional): The name of the Redis db file to be used. If this
argument is passed all instances of the redis.Redis
class will share a single instance of the embedded
redis server.
Returns:
None
"""
def unpatch_redis_StrictRedis():
"""
Unpatch the redis.StrictRedis() class of the redis module and restore the
original redis.StrictRedis() class.
Returns:
None
"""Usage Examples:
import redislite.patch
# Patch only StrictRedis class
redislite.patch.patch_redis_StrictRedis('/tmp/strict.db')
import redis
r = redis.StrictRedis() # Uses redislite.StrictRedis with embedded server
r.set('strict_key', 'strict_value')
# Check if patching is active
from redislite.patch import StrictRedis_Patched
print(f"StrictRedis patched: {StrictRedis_Patched}") # True
# Restore original StrictRedis class
redislite.patch.unpatch_redis_StrictRedis()Use redislite with existing libraries that depend on redis-py without code changes.
Usage Examples:
import redislite.patch
# Patch Redis before importing third-party libraries
redislite.patch.patch_redis('/tmp/app_cache.db')
# Now third-party libraries use embedded Redis
import redis_collections
import rq
from flask_caching import Cache
# redis_collections will use embedded Redis
cache_dict = redis_collections.Dict()
cache_dict['app_data'] = {'version': '1.0', 'users': 1000}
# RQ (Redis Queue) will use embedded Redis
from rq import Queue
q = Queue() # Uses embedded Redis server
# Flask-Caching will use embedded Redis
from flask import Flask
app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'redis'})
# All of these use the same embedded Redis instance at /tmp/app_cache.dbApply patches selectively based on application needs.
Usage Examples:
import redislite.patch
# Patch for testing only
def setup_test_environment():
redislite.patch.patch_redis() # No dbfile = separate instances
def teardown_test_environment():
redislite.patch.unpatch_redis()
# Patch for development with shared database
def setup_dev_environment():
redislite.patch.patch_redis('/tmp/dev_redis.db')
# Patch specific classes for gradual migration
def gradual_migration():
# Start with Redis only
redislite.patch.patch_redis_Redis('/tmp/migration.db')
# Later add StrictRedis
redislite.patch.patch_redis_StrictRedis('/tmp/migration.db')
# Conditional patching based on environment
import os
if os.getenv('USE_EMBEDDED_REDIS', 'false').lower() == 'true':
redislite.patch.patch_redis(os.getenv('REDIS_DB_FILE', '/tmp/app.db'))Handle patching states and errors gracefully.
Usage Examples:
import redislite.patch
# Check current patch status
def check_patch_status():
print(f"Redis patched: {redislite.patch.Redis_Patched}")
print(f"StrictRedis patched: {redislite.patch.StrictRedis_Patched}")
# Safe patching with error handling
def safe_patch(dbfile=None):
try:
if not redislite.patch.Redis_Patched:
redislite.patch.patch_redis_Redis(dbfile)
print("Redis successfully patched")
else:
print("Redis already patched")
if not redislite.patch.StrictRedis_Patched:
redislite.patch.patch_redis_StrictRedis(dbfile)
print("StrictRedis successfully patched")
else:
print("StrictRedis already patched")
except Exception as e:
print(f"Patching failed: {e}")
# Context manager for temporary patching
class TemporaryPatch:
def __init__(self, dbfile=None):
self.dbfile = dbfile
self.was_redis_patched = False
self.was_strictredis_patched = False
def __enter__(self):
self.was_redis_patched = redislite.patch.Redis_Patched
self.was_strictredis_patched = redislite.patch.StrictRedis_Patched
if not self.was_redis_patched:
redislite.patch.patch_redis_Redis(self.dbfile)
if not self.was_strictredis_patched:
redislite.patch.patch_redis_StrictRedis(self.dbfile)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if not self.was_redis_patched:
redislite.patch.unpatch_redis_Redis()
if not self.was_strictredis_patched:
redislite.patch.unpatch_redis_StrictRedis()
# Usage
with TemporaryPatch('/tmp/temp.db'):
import redis
r = redis.Redis() # Uses embedded server
r.set('temp', 'data')
# Patches are automatically removed hereoriginal_classes: defaultdict # Storage for original Redis classes
Redis_Patched: bool # Whether redis.Redis class has been patched
StrictRedis_Patched: bool # Whether redis.StrictRedis class has been patchedThese variables track the current patching state and can be used to check whether classes have been patched before applying or removing patches.
Install with Tessl CLI
npx tessl i tessl/pypi-redislite