coredis: Async Redis Client

6.5.1 · active · verified Sat Apr 11

coredis is a fast, async, and fully-typed Redis client for Python, offering support for Redis Cluster, Sentinel, and various Redis modules. It is built with structured concurrency using `anyio`, supporting both `asyncio` and `trio`. The library is actively maintained with frequent releases, often multiple times a month for bug fixes and minor features, with major architectural rewrites released periodically. The current version is 6.5.1.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates connecting to a single Redis instance, performing basic `SET`, `GET`, `INCR` operations, and using a command pipeline. It leverages `anyio.run` to execute the asynchronous code and uses `os.environ.get` for flexible Redis URL configuration.

import anyio
import coredis
import os

async def main() -> None:
    # Connect to Redis. Use a URL from an environment variable or default to localhost
    redis_url = os.environ.get('COREDIS_URL', 'redis://localhost:6379/0')
    # Optionally, decode responses to get Python strings instead of bytes
    client = coredis.Redis.from_url(redis_url, decode_responses=True)

    async with client:
        # Clear the database (use with caution in production!)
        print(f"Flushing database...")
        await client.flushdb()

        # Basic SET and GET operations
        print(f"Setting 'mykey' to 'hello'")
        await client.set("mykey", "hello")
        value = await client.get("mykey")
        print(f"Value of 'mykey': {value}")
        assert value == "hello"

        # Increment a numerical value
        print(f"Incrementing 'counter'")
        await client.set("counter", 1)
        assert await client.incr("counter") == 2
        print(f"Value of 'counter' after increment: {await client.get('counter')}")

        # Using a pipeline for multiple commands in a single round trip
        print("Running a pipeline...")
        async with client.pipeline() as pipeline:
            pipeline.incr("pipeline_counter")
            pipeline.get("pipeline_counter")
            pipeline.delete(["pipeline_counter"])
            results = await pipeline.execute()
            print(f"Pipeline results: {results}") # Expected: [1, '1', 1] (if decode_responses=True)

if __name__ == "__main__":
    # coredis uses anyio, supporting asyncio and trio. Specify your preferred backend.
    anyio.run(main, backend="asyncio")

view raw JSON →