XUtils

redis-py

The Python client for Redis.


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

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.

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.

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:

  • MULTI/EXEC: These are implemented as part of the Pipeline class. The pipeline is wrapped with the MULTI and EXEC statements by default when it is executed, which can be disabled by specifying transaction=False. See more about Pipelines below.

  • SUBSCRIBE/LISTEN: Similar to pipelines, PubSub is implemented as a separate class as it places the underlying connection in a state where it can\’t execute non-pubsub commands. Calling the pubsub method from the Redis client will return a PubSub instance where you can subscribe to channels and listen for messages. You can only call PUBLISH from the Redis client (see this comment on issue #151 for details).

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}


Articles

  • coming soon...