Skip to main content

Async Redis ORM for Python

Project description

ashredis - Redis Object Library

PyPI version Python versions

Overview

Python library for Redis object storage with sync/async interfaces.

Installation

pip install ashredis

Defining Models

Base Class Setup

from ashredis import AsyncRedisObject, RedisParams

REDIS_PARAMS = RedisParams(
    host="localhost",
    port=6379,
    password="your_password",
    db=0
)

class AsyncRedisObject(AsyncRedisObject):
    """Base class for all async models"""
    def __init__(self, key: str | int = None, path: list[str] = None):
        super().__init__(redis_params=REDIS_PARAMS, key=key, path=path)

Model Definition

class Product(AsyncRedisObject):
    """Product model example"""
    name: str
    price: float
    stock: int
    tags: list
    metadata: dict
    is_priority: bool
    last_update_ts: int
    
    __category__ = "product"  # Redis key prefix

Basic Operations

Save

from datetime import timedelta, datetime

async with Product(key="prod_123") as p:
    p.name = "Wireless Headphones"
    p.price = 129.99
    p.stock = 25
    p.tags = ["audio", "wireless"]
    p.metadata = {"brand": "Sony", "color": "black"}
    p.is_priority = True
    p.last_update_ts = int(datetime.now().timestamp() * 1000)
    
    await p.save(ttl=timedelta(hours=2))  # Optional TTL

Load

async with Product(key="prod_123") as p:
    if await p.load():
        print(f"Product: {p.name}")
        print(f"Price: ${p.price}")
        print(f"In Stock: {p.stock}")

Update

async with Product(key="prod_123") as p:
    p.stock = 20
    await p.save()

Delete

async with Product(key="prod_123") as p:
    if await p.delete():
        print("Product deleted successfully")

Advanced Usage

Hierarchical Keys

# Creates key "product:electronics:audio:prod_123"
async with Product(key="prod_123", path=["electronics", "audio"]) as p:
    p.name = "Studio Headphones"
    await p.save()

Bulk Operations

# Get all products
all_products = await Product().load_all()

# Get sorted by price (descending)
expensive_first = await Product().load_sorted("price", reverse_sorted=True)

# Get recently updated
recent = await Product().load_for_time(
    ts_field="last_update_ts",
    time_range=timedelta(days=1)
)

Copy

async with Product(key="prod_123") as p:
    await p.copy(p2)  # Copies all data from original
    p.price = 90.00
    await p.save()

Data Conversion

# Export to dict
product_data = {
    "name": "Gaming Mouse",
    "price": 59.99,
    "stock": 30
}

async with Product(key="mouse_01") as p:
    p.load_dict(product_data)
    await p.save()
    
    # Verify
    exported = p.get_dict()
    print(exported)

Get TTL

from datetime import timedelta

async with Product(key="temp_product") as p:
    p.name = "Temporary Offer"
    await p.save(ttl=timedelta(minutes=30))
    
    # Check remaining time
    ttl = await p.get_ttl()
    print(f"Product expires in {ttl} seconds")

Stream In Interval

from datetime import datetime, timedelta

# Get events from specific time range
start_ts = int((datetime.now() - timedelta(hours=1)).timestamp() * 1000)
end_ts = int(datetime.now().timestamp() * 1000)
events = await Product().get_stream_in_interval(start_ts, end_ts)

for event in events:
    print(f"Event: {event.name} at {event.last_update_ts}")

Stream Listening

async def handle_event(event):
    print(f"New product update: {event.name}")

# Start listening for events
async def monitor_updates():
    product = Product(path=["electronics"])
    await product.listen_for_stream(
        callback=handle_event,
        delay=1  # check every second
    )

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.1.3.tar.gz (10.7 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.1.3-py3-none-any.whl (11.9 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: ashredis-1.1.3.tar.gz
  • Upload date:
  • Size: 10.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for ashredis-1.1.3.tar.gz
Algorithm Hash digest
SHA256 f3d2bbebba6354c7176321b46695c9008ac080319ad2c17bf807093b242e6106
MD5 bb8b4a7cb9f7576cf59eea671b9a7d59
BLAKE2b-256 d2dff9e9ff82a1e8b627b9eff23f37b2eb5e3a02c4587518e9fc89641c89e1e7

See more details on using hashes here.

File details

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

File metadata

  • Download URL: ashredis-1.1.3-py3-none-any.whl
  • Upload date:
  • Size: 11.9 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.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 41bd4f04cf4787c3174d554ed2cfd1e42f85c4d224ac18c11a795ef4b3571f49
MD5 0fb5233b64b0e611db708a1cb8d297ae
BLAKE2b-256 803a21718c15109009126dc349602018cf473db601556f3f6c80cda27283aff5

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