Skip to main content

Async Redis ORM for Python

Project description

ashredis - Async Redis ORM for Python

PyPI version Python versions

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


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.2.tar.gz (8.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ashredis-1.0.2-py3-none-any.whl (7.2 kB view details)

Uploaded Python 3

File details

Details for the file ashredis-1.0.2.tar.gz.

File metadata

  • Download URL: ashredis-1.0.2.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

Hashes for ashredis-1.0.2.tar.gz
Algorithm Hash digest
SHA256 3508b69545b4800127f3d363d22d70aaca6f281273bbfe989448c4e235832eda
MD5 5536417ddd10af8aac666cb516d5f1e9
BLAKE2b-256 89392fa3b8e80202f91f5360ac53e69055942d0ed3e9bae7326b5585adfa1508

See more details on using hashes here.

File details

Details for the file ashredis-1.0.2-py3-none-any.whl.

File metadata

  • Download URL: ashredis-1.0.2-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

Hashes for ashredis-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 88280fcf2625bbe239fd661fd6d22f70962ae5917014188894f76692e5e6c688
MD5 636bcc4c03797a959d0b5bc529225f2e
BLAKE2b-256 d61916934d27cc1ed3b66097ec13254212acbe51f43020f48af3f6a51bc3e9cc

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page