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.3.tar.gz
(10.0 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
ashredis-1.0.3-py3-none-any.whl
(12.1 kB
view details)
File details
Details for the file ashredis-1.0.3.tar.gz.
File metadata
- Download URL: ashredis-1.0.3.tar.gz
- Upload date:
- Size: 10.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7bc4462c61804b43a6df2106d8d86ab5714f0704a35ad71c04c378c948263639
|
|
| MD5 |
37342ba5429d7875183c04b043a0d593
|
|
| BLAKE2b-256 |
d259916403e260accc7e113745d4be2485ff04d1cdd90d1b03e71779e45bfce1
|
File details
Details for the file ashredis-1.0.3-py3-none-any.whl.
File metadata
- Download URL: ashredis-1.0.3-py3-none-any.whl
- Upload date:
- Size: 12.1 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 |
66e0b622243b62cffb22f6df27134c309b8cb00ed7caa9940b7dfcd362488dac
|
|
| MD5 |
48a269c413704633da31a9b7b343b12e
|
|
| BLAKE2b-256 |
2e0d14501bde60d7105f8c06708d820c8be09075dc1b55c01642c84b1e8d8bf0
|