redis-py README

The project's README from github.com/redis/redis-py. As one markdown file: README.md.

redis-py

The Python interface to the Redis key-value store.

CI docs MIT licensed pypi pre-release codecov

Installation | Usage | Advanced Topics | Contributing


Note: redis-py 5.0 is the last version of redis-py that supports Python 3.7, as it has reached end of life. redis-py 5.1 supports Python 3.8+.
Note: redis-py 6.1.0 is the last version of redis-py that supports Python 3.8, as it has reached end of life. redis-py 6.2.0 supports Python 3.9+.


How do I Redis?

Learn for free at Redis University

Try the Redis Cloud

Dive in developer tutorials

Join the Redis community

Work at Redis

Installation

Start a redis via docker (for Redis versions >= 8.0):

docker run -p 6379:6379 -it redis:latest

Start a redis via docker (for Redis versions < 8.0):

docker run -p 6379:6379 -it redis/redis-stack:latest

To install redis-py, simply:

$ pip install redis

For faster performance, install redis with hiredis support, this provides a compiled response parser, and for most cases requires zero code changes. By default, if hiredis >= 1.0 is available, redis-py will attempt to use it for response parsing.

$ pip install "redis[hiredis]"

Looking for a high-level library to handle object mapping? See redis-om-python!

Supported Redis Versions

The most recent version of this library supports Redis version 7.2, 7.4, 8.0, 8.2, 8.4, 8.6 and 8.8.

The table below highlights version compatibility of the most-recent library versions and redis versions.

Library version Supported redis versions
3.5.3 <= 6.2 Family of releases
>= 4.5.0 Version 5.0 to 7.0
>= 5.0.0 Version 5.0 to 7.4
>= 6.0.0 Version 7.2 to current

Usage

Basic Example

>>> import redis
>>> r = redis.Redis(host='localhost', port=6379, db=0)
>>> r.set('foo', 'bar')
True
>>> r.get('foo')
b'bar'

The above code connects to localhost on port 6379, sets a value in Redis, and retrieves it. All responses are returned as bytes in Python, to receive decoded strings, set decode_responses=True. For this, and more connection options, see these examples.

RESP3 Support

redis-py supports RESP3 starting with version 5.0. Starting with redis-py 8.0, clients use RESP3 on the wire by default while preserving legacy RESP2-compatible Python response shapes for existing applications.

Set protocol=3 explicitly when your application should receive RESP3-specific response shapes or when you want the wire protocol choice to be visible in code. To force RESP2 on the wire, set protocol=2. To opt in to protocol-independent response shapes, set legacy_responses=False.

For new projects, we recommend opting out of legacy response compatibility by setting legacy_responses=False. This makes redis-py return unified Python response shapes for affected commands whether the connection uses RESP2 or RESP3. Existing applications can keep the default legacy-compatible behavior while they migrate response handling at their own pace.

>>> import redis
>>> r = redis.Redis(host='localhost', port=6379, db=0, legacy_responses=False)

See the unified responses migration guide for activation instructions and command-by-command response differences. For RESP3-specific behavior, see the RESP3 features guide.

Connection Pools

By default, redis-py uses a connection pool to manage connections. Each instance of a Redis class receives its own connection pool. You can however define your own redis.ConnectionPool.

>>> pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
>>> r = redis.Redis(connection_pool=pool)

Alternatively, you might want to look at Async connections, or Cluster connections, or even Async Cluster connections.

Redis Commands

There is built-in support for all of the out-of-the-box Redis commands. They are exposed using the raw Redis command names (HSET, HGETALL, etc.) except where a word (i.e. del) is reserved by the language. The complete set of commands can be found here, or the documentation.

Advanced Topics

The official Redis command documentation does a great job of explaining each command in detail. redis-py attempts to adhere to the official command syntax. There are a few exceptions:

For more details, please see the documentation on advanced topics page.

Pipelines

The following is a basic example of a Redis pipeline, a method to optimize round-trip calls, by batching Redis commands, and receiving their results as a list.

>>> pipe = r.pipeline()
>>> pipe.set('foo', 5)
>>> pipe.set('bar', 18.5)
>>> pipe.set('blee', "hello world!")
>>> pipe.execute()
[True, True, True]

PubSub

The following example shows how to utilize Redis Pub/Sub to subscribe to specific channels.

>>> r = redis.Redis(...)
>>> p = r.pubsub()
>>> p.subscribe('my-first-channel', 'my-second-channel', ...)
>>> p.get_message()
{'pattern': None, 'type': 'subscribe', 'channel': b'my-second-channel', 'data': 1}

Redis’ search and query capabilities default dialect

Release 6.0.0 introduces a client-side default dialect for Redis’ search and query capabilities. By default, the client now overrides the server-side dialect with version 2, automatically appending DIALECT 2 to commands like FT.AGGREGATE and FT.SEARCH.

Important: Be aware that the query dialect may impact the results returned. If needed, you can revert to a different dialect version by configuring the client accordingly.

>>> from redis.commands.search.field import TextField
>>> from redis.commands.search.query import Query
>>> from redis.commands.search.index_definition import IndexDefinition
>>> import redis

>>> r = redis.Redis(host='localhost', port=6379, db=0)
>>> r.ft().create_index(
>>>     (TextField("name"), TextField("lastname")),
>>>     definition=IndexDefinition(prefix=["test:"]),
>>> )

>>> r.hset("test:1", "name", "James")
>>> r.hset("test:1", "lastname", "Brown")

>>> # Query with default DIALECT 2
>>> query = "@name: James Brown"
>>> q = Query(query)
>>> res = r.ft().search(q)

>>> # Query with explicit DIALECT 1
>>> query = "@name: James Brown"
>>> q = Query(query).dialect(1)
>>> res = r.ft().search(q)

You can find further details in the query dialect documentation.

Multi-database client (Active-Active)

The multi-database client allows your application to connect to multiple Redis databases, which are typically replicas of each other. It is designed to work with Redis Software and Redis Cloud Active-Active setups. The client continuously monitors database health, detects failures, and automatically fails over to the next healthy database using a configurable strategy. When the original database becomes healthy again, the client can automatically switch back to it.
This is useful when:

  1. You have more than one Redis deployment. This might include two independent Redis servers or two or more Redis databases replicated across multiple active-active Redis Enterprise clusters.
  2. You want your application to connect to one deployment at a time and to fail over to the next available deployment if the first deployment becomes unavailable.

For the complete failover configuration options and examples, see the Multi-database client docs.

Bulk hash ingestion (HIMPORT)

Redis 8.10 adds the HIMPORT command family for loading many hashes that share the same set of field names: register the field names once with himport_prepare, then create each hash by sending only its values. Keys written this way are regular hashes — every hash command works on them.

r.himport_prepare("users", ["name", "email", "age"])
r.himport_set("user:1", "users", ["alice", "[email protected]", "25"])
r.himport_set("user:2", "users", ["bob", "[email protected]", "30"])
r.himport_discard("users")  # => 1

Values pair positionally with the prepared fields. Hash enumeration order (HGETALL, HKEYS) is not guaranteed to match the prepare order.

Fieldsets are connection state. A prepared fieldset lives in the server-side session of the physical connection that prepared it: it is invisible to other connections and destroyed by a disconnect or RESET. redis-py handles this for you — himport_prepare records the fieldset in a client-level registry, and the PREPARE is applied lazily on whatever pooled connection serves each himport_set (and re-applied automatically after a reconnect, RESET, or Sentinel/cluster failover). You declare each fieldset once per client with himport_prepare; there is no constructor argument for it.

For the highest ingestion throughput, send the PREPARE and its SETs in one pipeline — a single batch always executes on one connection:

with r.pipeline(transaction=False) as pipe:
    pipe.himport_prepare("users", ["name", "email", "age"])
    for uid, row in rows:
        pipe.himport_set(f"user:{uid}", "users", row)
    pipe.execute()

The automatic re-prepare applies to direct calls only, not to commands inside pipeline/transaction blocks: a batched himport_set relies on the single pre-flight PREPARE in that batch.

With RedisCluster, himport_prepare / himport_discard / himport_discard_all update the client's shared, cluster-wide registry and return immediately — like the standalone API, they perform no server I/O of their own. The server-side PREPARE (and, after a discard, DISCARD) is applied lazily on each node's connection the next time it serves an himport_set, and re-applied after reconnects or failover; himport_set itself routes by the key's hash slot. A discard is therefore not removed from every server session at once: each connection drops the fieldset on its next himport_set (or on disconnect). With Sentinel, call himport_prepare on the long-lived client returned by master_for(...); the fieldset survives failover automatically. HIMPORT is not supported on the multi-database (Active-Active) client.

The async client mirrors this exactly:

await r.himport_prepare("users", ["name", "email", "age"])
await r.himport_set("user:1", "users", ["alice", "[email protected]", "25"])

Author

redis-py is developed and maintained by Redis Inc. It can be found here, or downloaded from pypi.

Special thanks to:

Redis

redis-py (redis/redis-py)

Searching Database…

13.7K ·GitHub
这是干什么的?redis-py 是 Redis 键值数据库的官方 Python 客户端,也就是你的 Python 代码用来和 Redis 服务器通信的接口。
那 Redis 本身是包含在这个包里,还是我要单独去运行它?它只是一个客户端库,不是服务器:你把 redis-py 加进自己的 Python 项目,然后让它连接到别处运行的 Redis 服务器。README 的快速上手部分是用 Docker 起一个 Redis(Redis 8.0+)。
我怎么发起第一次调用?先从 PyPI 安装(pip install redis),然后创建一个客户端——基础示例会连接到 localhost:6379,写入一个值再把它读回来。
我需要哪个 Python 和 Redis 版本?当前版本线需要 Python 3.9+(对 3.8 的支持在 6.1.0 就结束了),支持 Redis 7.2 到 8.8;项目还提供一张兼容性表,把旧版库和对应的旧版 Redis 一一对应起来。
第一次运行有什么坑吗?最经典的一个:默认返回的是字节(bytes),所以如果你想要正常的字符串而不是 b'...' 这样的值,连接时要传 decode_responses=True。
我是不是得先会 Redis 命令?会的话有帮助——方法名基本和原始命令名一致(HSET、HGETALL 等),只有在和 Python 保留字冲突时才会改名(比如 del)。事务和发布/订阅是通过 Pipeline 和 PubSub 对象来操作的,而不是直接调用 MULTI/EXEC 或 SUBSCRIBE。
我用什么操作系统有影响吗?没有——它是 PyPI 上的纯 Python 包,Python 能跑的地方它就能跑,只需要能通过网络访问一台 Redis 服务器,本地或远程都行。
能用 asyncio、Redis Cluster 或者 Sentinel 吗?可以——除了每个客户端默认的连接池之外,还有专门的异步连接、Cluster 连接和异步 Cluster 连接,Sentinel 方案也支持,字段发现和故障转移都替你处理好了。你也可以接入自己的 redis.ConnectionPool。
Pipeline 和 Pub/Sub 是怎么工作的?Pipeline 会把命令打包批量发送,减少来回往返,执行时还会自动套上 MULTI/EXEC(用 transaction=False 可以关掉)。Pub/Sub 则是 通过 client.pubsub() 单独创建的 PubSub 对象,因为订阅中的连接没法执行普通命令;只有 PUBLISH 是走主客户端的。
它支持 Redis 的搜索和查询功能吗?支持,搜索和查询命令都是内置的。从 6.0 开始,客户端会默认在 FT.SEARCH、FT.AGGREGATE 这类命令后面附加 DIALECT 2,README 也提醒方言设置可能改变返回的结果,所以你可以自行配置成别的版本。
redis-om-python 是什么?是 README 里推荐的一个配套高级库,用于对象映射——如果你不想直接写 Redis 命令,而是想操作 Python 对象,它就是构建在 redis-py 之上的 ORM 风格方案。
Creator
redis
Size
15.6 MB
Stars
13.7K
Age
16y
Commits · 90 Days