Skip to main content

WRedis

Python 3.9+ License: MIT Ruff PyPI Coverage LTS

WRedis — Production-ready Python library for Redis with sync/async APIs, cache decorators, high availability, and comprehensive type safety.

image

Installation

pip install wredis

Requires Python 3.9+ and a running Redis server (local or remote).


Key Technologies and Libraries

wredis is built on modern, high-performance Python database standards:

  • Redis & redis-py: Primary client driver supporting sync, async, Sentinel, and Cluster.
  • Loguru: Structured, thread-safe diagnostic logging.
  • Pytest & Fakeredis: Mocked and live test suite execution.
  • Python 3.9+: Modern synchronous and asynchronous runtime.

Enterprise Forensic Audit & Key Space Management

wredis provides an automated stream-based audit trail (_forensic_audit_log) for monitoring mutations across key-spaces.

  • Disabled by default: Pass forensic=True when instantiating managers (e.g. RedisHashManager(..., forensic=True)) to enable automatic audit logging.
  • Stream-based Audit Trail: Append-only stream recording action, target key, pre-state, and post-state JSON snapshots.
  • Zero Overhead: Completely isolated log streams.

Features

Feature Description
Sync & Async Full support for both synchronous and asynchronous (asyncio) APIs
Cache Decorators @cache / @async_cache with hit/miss metrics and TTL management
High Availability Redis Sentinel and Cluster support
13 Data Structures KeyValue, Bitmap, Hash, Set, SortedSet, Stream, Queue, Pub/Sub, Geo, HyperLogLog, Pipeline, Transaction
Error Handling Proper exception hierarchy, no silent failures
Type Safety Fully type-hinted, mypy clean
Compression Optional gzip compression for queue messages
Validation Built-in key, TTL, and value validation

Quick Start

from wredis.cache import RedisCacheManager

cache = RedisCacheManager(host="localhost")

@cache("my_cache", ttl=60)
def expensive_function(param: str) -> dict:
    return {"result": f"processed {param}"}

data = expensive_function("hello")  # cached for 60s

Modules

Key-Value (Direct Ephemeral RAM Storage)

from wredis.keyvalue import RedisKeyValueManager

kv = RedisKeyValueManager(host="localhost", port=6379)

# Store raw binary bytes with 5-second TTL (ideal for high-throughput multimedia offload & claim-check)
kv.setex("frame:1001", ttl=5, value=raw_bytes)

# Retrieve raw bytes without string encoding conversion
payload = kv.get_bytes("frame:1001")

# Also supports dictionaries/JSON and strings:
kv.set("user:meta", {"id": 101, "role": "admin"})
meta = kv.get("user:meta")  # Automatically parsed as dict

Methods: set, setex, get, get_bytes, delete, exist, exists, close


Bitmap

from wredis.bitmap import RedisBitmapManager

bm = RedisBitmapManager(host="localhost")
bm.set_bit("my_bitmap", offset=5, value=1)
print(bm.get_bit("my_bitmap", 0))   # 0
print(bm.count_bits("my_bitmap"))    # 1

Methods: set_bit, get_bit, exist, count_bits, get_ttl, extend_ttl, delete_bitmap


Hash

from wredis.hash import RedisHashManager

hm = RedisHashManager(host="localhost")
hm.create_hash("users", "user:1", {"name": "Alice", "age": 30}, ttl=60)
user = hm.read_hash("users", "user:1")
all_users = hm.read_all_hash("users")
hm.update_hash("users", "user:1", {"age": 31})
hm.delete_hash_field("users", "user:2")
hm.delete_hash("users")
exists = hm.exist("users")

Methods: create_hash, read_hash, exist, update_hash, delete_hash_field, delete_hash, read_all_hash, get_ttl, extend_ttl


Queue

from wredis.queue import RedisQueueManager

# Producer
qm = RedisQueueManager(host="localhost")
qm.publish("tasks", {"id": 1, "task": "process_image"}, ttl=30)
exists = qm.exist("tasks")

Methods: publish, on_message, exist, start, stop, wait, get_queue_length, delete_queue


Pub/Sub

from wredis.pubsub import RedisPubSubManager

pbm = RedisPubSubManager(host="localhost")

# Producer
pbm.publish_message("notifications", "Hello, Redis!")
pbm.publish_message("alerts", {"severity": "high", "message": "Disk full"})
exists = pbm.exist("notifications")

# Consumer
@pbm.on_message("notifications")
def handle(msg):
    print(f"Received: {msg}")

pbm.stop_listeners()

Methods: publish_message, on_message, exist, stop_listeners


Streams

from wredis.streams import RedisStreamManager

sm = RedisStreamManager(host="localhost")

# Producer
sm.add_to_stream("events", {"action": "login", "user": "alice"})
exists = sm.exist("events")

# Consumer
@sm.on_message("events", group_name="my_group", consumer_name="worker_1")
def process(data):
    print(f"Processing: {data}")

sm.wait()

Methods: add_to_stream, on_message, exist, read_from_stream, wait, delete_stream


Sets

from wredis.sets import RedisSetManager

sm = RedisSetManager(host="localhost")
sm.add_to_set("tags", "python", "redis", "wredis")
members = sm.get_set_members("tags")
print(sm.is_member("tags", "python"))  # True
sm.remove_from_set("tags", "redis")
exists = sm.exist("tags")

Methods: add_to_set, get_set_members, exist, is_member, remove_from_set, get_ttl, extend_ttl, delete_set


Sorted Sets

from wredis.sortedset import RedisSortedSetManager

ssm = RedisSortedSetManager(host="localhost")
ssm.add_to_sorted_set("leaderboard", 100, "player1")
ssm.add_to_sorted_set("leaderboard", 200, "player2")
ssm.add_to_sorted_set("leaderboard", 150, "player3")

top = ssm.get_sorted_set_reverse("leaderboard", with_scores=True)
rank = ssm.get_rank("leaderboard", "player2")
score = ssm.get_score("leaderboard", "player3")
ssm.increment_score("leaderboard", 50, "player3")
exists = ssm.exist("leaderboard")

Methods: add_to_sorted_set, get_sorted_set, get_sorted_set_reverse, exist, remove_from_sorted_set, get_rank, get_score, delete_sorted_set, set_ttl, get_ttl, increment_score, get_sorted_set_by_score


Geo

from wredis.geo import RedisGeoManager

gm = RedisGeoManager(host="localhost")
gm.add_location("places", "Central Park", 40.785091, -73.968285)
dist = gm.distance("places", "Central Park", "Times Square")
exists = gm.exist("places")

Methods: add_location, exist, distance, geo_radius, get_location, delete_geo


Advanced Patterns

For complex use cases, WRedis supports:

  • Pipelines & Transactions: Atomic operations and batch execution.
  • Custom Key Generation: Full control over cache key naming.
  • Connection Tuning: Optimization for high-traffic environments.
  • Granular Error Handling: Specific exception hierarchy for robust applications.

Check the Full Documentation for detailed guides.


HyperLogLog

from wredis.hyperloglog import RedisHyperLogLogManager

hll = RedisHyperLogLogManager(host="localhost")
hll.add("visitors", "user1", "user2", "user3")
count = hll.count("visitors")
hll.merge("all_visitors", "visitors")
exists = hll.exist("visitors")

Methods: add, exist, count, merge, get_all, delete_hyperloglog


Pipeline

from wredis.pipeline import RedisPipelineManager

pm = RedisPipelineManager(host="localhost")
pm.set_get("key1", "value1")
results = pm.mget_pipeline("key1", "key2", "key3")

Methods: set_get, mget_pipeline


Transaction

from wredis.transaction import RedisTransactionManager

tm = RedisTransactionManager(host="localhost")
result = tm.get_and_set("counter", "1")

Methods: get_and_set


Cache Decorator

from wredis.cache import RedisCacheManager

cache = RedisCacheManager(host="localhost")

@cache(ttl=60)
def get_user(user_id: str) -> dict:
    return {"id": user_id, "name": "Alice"}

# Call decorated function — results are cached
user = get_user("42")

Methods: @cache (sync), @async_cache (async), invalidate, clear, get_stats


High Availability

Sentinel

from wredis.ha.sentinel import RedisSentinelManager

sm = RedisSentinelManager(
    sentinel_hosts=[("sentinel1", 26379), ("sentinel2", 26379)],
    service_name="mymaster",
    password="optional",
)

Cluster

from wredis.ha.cluster import RedisClusterManager

cm = RedisClusterManager(
    startup_nodes=[{"host": "node1", "port": 6379}],
    password="optional",
)

Configuration

All managers accept common connection parameters:

Parameter Default Description
host "localhost" Redis server hostname
port 6379 Redis server port
db 0 Redis database number
password None Redis password
verbose True Enable logging
decode_responses False Decode responses to strings

Queue-specific:

Parameter Default Description
poll_interval 1 Seconds between polls for empty queues
max_retries 3 Maximum retry attempts on error
compress False Enable gzip compression for messages

Testing

# Run all tests
pytest tests/

# Run with coverage
pytest --cov=wredis tests/

# Run specific module tests
pytest tests/unit/test_queue.py
pytest tests/integration/test_all_modules_integration.py

License

MIT — see LICENSE for details.

Metadata

Release files for wredis 1.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for wredis 1.1.0
File Size Uploaded Provenance Actions
wredis-1.1.0.tar.gz 2.2 MB Without provenance Details for wredis-1.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for wredis 1.1.0
File Interpreter ABI Platform Actions
wredis-1.1.0-py3-none-any.whl Python 3 none any Details for wredis-1.1.0-py3-none-any.whl

Total release size: 2.2 MB

Release files / wredis-1.1.0.tar.gz

Download URL wredis-1.1.0.tar.gz
Size 2.2 MB
Tags Source
SHA-256 checksum
How to use checksums
c115f4ba407475346f9e6fc60c608c9f7fad81caeef888b7117345b87e8be0b7
BLAKE2b-256 checksum
How to use checksums
cf7cb8dd82b62c85b2ec1cf9b4f280fe96661da18ba6578d361090b49817a764
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.5

Release files / wredis-1.1.0-py3-none-any.whl

Download URL wredis-1.1.0-py3-none-any.whl
Size 70.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
00ed9fa62371f1f1ceac4ecad7f5c4333aaf3dceb245d53a4011831394a7b14f
BLAKE2b-256 checksum
How to use checksums
432f3a1823918f93030cab9722db47cc8c96c477b47c82b7341cbdd1fab57759
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.5

Security for wredis 1.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page