aioredis
aioredis is an `asyncio` (PEP 3156) Redis client library providing asynchronous support for Redis. Currently at version 2.0.1, it underwent a complete rewrite in version 2.0.0 to align its API closely with the `redis-py` library, making it easier to adapt synchronous `redis-py` code for async applications. It is actively maintained with frequent updates.
Warnings
- breaking Version 2.0.0 of aioredis is a complete rewrite and introduces significant backward-incompatible API changes. It now closely follows the `redis-py` API, so existing code from v1.x will break.
- breaking Factory functions like `aioredis.create_redis()`, `aioredis.create_redis_pool()`, and `aioredis.create_pool()` are no longer available in v2.x.
- breaking The `loop` argument for specifying an `asyncio` event loop has been deprecated in v1.3.1 for Python 3.8+ and effectively removed in v2.x. `aioredis` now relies on the implicit event loop of `asyncio`.
- breaking In v2.x, connection pools are lazy-filled, meaning connections are created on demand, unlike v1.x where `minsize` pre-filled the pool.
- breaking The `Channel` abstraction over PubSub, present in v1.x, has been removed in v2.x to align with `redis-py`'s API.
- gotcha By default, `aioredis` returns bytes for most Redis commands. To automatically decode responses to strings, you must explicitly pass `decode_responses=True` during client initialization.
- breaking Version 1.0.0 dropped support for Python 3.3 and 3.4. It also changed the return format for sorted set commands (with `withscores`) and `hscan` to lists of tuples instead of plain lists or mixed key-value lists.
Install
-
pip install aioredis -
pip install aioredis hiredis
Imports
- from_url
import aioredis redis = aioredis.from_url(...)
- Redis
from aioredis import Redis redis = Redis(connection_pool=...)
- ConnectionPool
from aioredis import ConnectionPool pool = ConnectionPool.from_url(...)
Quickstart
import asyncio
import aioredis
import os
async def main():
# Connect to Redis using a URL. For production, use environment variables.
# decode_responses=True decodes bytes to strings automatically.
redis_url = os.environ.get('REDIS_URL', 'redis://localhost')
redis = aioredis.from_url(
redis_url,
encoding="utf-8",
decode_responses=True
)
try:
await redis.set("my-key", "value")
val = await redis.get("my-key")
print(f"Retrieved value: {val}")
# Example with a pipeline
async with redis.pipeline(transaction=True) as pipe:
result = await pipe.incr("counter").incr("counter").execute()
print(f"Pipeline result: {result}")
finally:
# Ensure the connection pool is closed gracefully
await redis.close()
await redis.wait_closed()
if __name__ == "__main__":
asyncio.run(main())