Async Redis ORM for Python
Project description
ashredis - Async Redis ORM for Python
ashredis is an asynchronous Redis Object-Relational Mapping (ORM) library for Python that provides a simple way to interact with Redis using Python objects.
Features
- Fully asynchronous using
redis.asyncio - Type annotations for all fields
- Automatic serialization/deserialization
- TTL (Time-To-Live) support
- Querying and sorting capabilities
- Redis Stream integration
Installation
pip install ashredis
Basic Usage
import asyncio
import time
from datetime import timedelta
from ashredis.model import RedisObject
# Define your Redis-backed model
class User(RedisObject):
username: str
email: str
last_login: int # timestamp in milliseconds
__category__ = "user" # Redis key prefix
__default_key__ = "default_user" # Default key if not specified
async def main():
# Create and save a user
user = User(key="user123")
user.username = "johndoe"
user.email = "john@example.com"
user.last_login = int(time.time() * 1000)
# Save with 1 hour TTL
await user.save(ttl=timedelta(hours=1))
# Load the user
await user.load()
print(user.username) # "johndoe"
# Context manager usage (auto-closes connection)
async with User(key="user456") as new_user:
new_user.username = "janedoe"
await new_user.save()
await new_user.load()
print(new_user.username) # "janedoe"
asyncio.run(main())
Comprehensive Guide
Model Definition
Define your Redis-backed models by subclassing RedisObject:
class Product(RedisObject):
name: str
price: float
stock: int
tags: list # automatically serialized to JSON
metadata: dict # automatically serialized to JSON
__category__ = "product"
Connection Management
Initialize with Redis connection parameters:
class MyModel(RedisObject):
def __init__(self, key: str | int = None, path: list[str] = None):
super().__init__(
host="localhost",
port=6379,
password="your_password",
db=0,
key=key,
path=path
)
Or use context manager for automatic connection handling:
async with Product(key="prod123") as product:
await product.load()
CRUD Operations
Create/Save
product = Product(key="prod123")
product.name = "Laptop"
product.price = 999.99
product.stock = 10
product.tags = ["electronics", "computers"]
await product.save()
# With TTL (Time-To-Live)
await product.save(ttl=timedelta(days=1))
# With stream event
await product.save(stream=True)
Read/Load
# Load by key
await product.load(key="prod123")
# Check if exists
exists = await product.load()
if exists:
print("Product exists!")
Update
# Load by key
await product.load(key="prod123")
product.price = 899.99 # Update price
await product.save()
Delete
await product.delete(key="prod123")
Querying
Load All Records
all_products = await Product().load_all()
With Pagination
# Get first 10 products
products = await Product().load_all(limit=10)
# Get next 10 products
products = await Product().load_all(offset=10, limit=10)
Load Sorted
# Sort by price (ascending)
products = await Product().load_sorted("price")
# Sort by price (descending)
products = await Product().load_sorted("price", reverse_sorted=True)
Time-based Queries
# Get products updated in last 24 hours
recent_products = await Product().load_for_time(
ts_field="last_updated",
time_range=timedelta(days=1)
)
# Get sorted by timestamp
recent_products = await Product().load_for_time(
ts_field="last_updated",
time_range=timedelta(days=1),
sort=True
)
Advanced Features
Hierarchical Keys
# Creates key like "product:category:electronics:123"
product = Product(key="123", path=["category", "electronics"])
Stream Integration
# Save with stream event
await product.save(stream=True)
# Get stream events
events = await product.get_stream_in_interval(
start_ts=int(time.time() * 1000) - 3600000, # 1 hour ago
end_ts=int(time.time() * 1000) # now
)
# Listen for stream events
async def callback(event):
print("New event:", event.get_dict())
await product.listen_for_stream(callback)
TTL Management
# Set TTL
await product.save(ttl=timedelta(hours=2))
# Get remaining TTL
ttl_seconds = await product.get_ttl()
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
ashredis-1.0.1.tar.gz
(8.5 kB
view details)
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file ashredis-1.0.1.tar.gz.
File metadata
- Download URL: ashredis-1.0.1.tar.gz
- Upload date:
- Size: 8.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
12d593d6a35af8f61f8357417f55baec848e9799db370f95bbe39bfa9ebedcc1
|
|
| MD5 |
950a68eb02809d5d58b6048c785428ad
|
|
| BLAKE2b-256 |
29232fc80d9ed18d72153a2d4be03ac04f7fb1b0deb256dc73f70a5d7df295be
|
File details
Details for the file ashredis-1.0.1-py3-none-any.whl.
File metadata
- Download URL: ashredis-1.0.1-py3-none-any.whl
- Upload date:
- Size: 7.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
18bbea4efc396e81dd525889a014e7a7c055b796272cdc8fddde8e96f823de3d
|
|
| MD5 |
c8b8a9f8ec9510a0e9ee8e3d6f3df8a5
|
|
| BLAKE2b-256 |
beecc641a017c4cf09e1a3a41c7a88b8f37316cf0e8bc6dab1388f0dfeb2a1c3
|