walrus: Redis Utilities

0.9.8 · active · verified Fri Apr 17

walrus is a Python library providing a set of high-level utilities and abstractions for working with Redis. It offers an object-oriented interface to Redis data structures, including hashes, lists, sets, streams, and also provides features like caching, full-text search, and a graph API. The current version is 0.9.8, with releases occurring periodically, often in response to changes in its underlying `redis-py` dependency.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates connecting to a Redis instance and utilizing some of walrus's core features: a Hash for storing structured data, a Set for unique items, and a cached decorator for expensive function calls. Environment variables are used for Redis connection details for robustness.

from walrus import Database

# Connect to Redis (defaults to localhost:6379, db=0)
db = Database(
    host=os.environ.get('REDIS_HOST', 'localhost'),
    port=int(os.environ.get('REDIS_PORT', 6379)),
    db=int(os.environ.get('REDIS_DB', 0))
)

# Use a Hash
user_data = db.Hash('user:123')
user_data['name'] = 'Alice'
user_data['email'] = 'alice@example.com'
print(f"User name: {user_data['name']}")

# Use a Set
tags = db.Set('post:tags:my-post')
tags.add('python', 'redis', 'tutorial')
print(f"Post tags: {list(tags)}")

# Use a Cache
@db.cache.cached()
def get_expensive_data(key):
    print(f"Fetching data for {key}...")
    return {'value': key.upper(), 'timestamp': 'now'}

print(get_expensive_data('test'))
print(get_expensive_data('test')) # This call will be cached

view raw JSON →