aioredis

2.0.1 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

This quickstart demonstrates connecting to Redis using `aioredis.from_url`, setting and retrieving a key, and using a transaction pipeline. It emphasizes graceful connection shutdown and the recommended `decode_responses` parameter for automatic string decoding.

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())

view raw JSON →