Introduction
Redis is a high-performance in-memory data store used as a cache, message broker, database, or queue. It supports a variety of data structures: strings, lists, sets, hashes, and more. For Python, the official client is redis-py, which provides a convenient interface to Redis functionality.
Redis-py is the most popular and reliable client for working with Redis in Python applications. The library is actively developed and maintained by the community, offering a simple and intuitive API for interacting with a Redis server.
What is the redis-py Library
Redis-py is the official Python library for working with Redis, providing full support for all Redis features. The library is written in pure Python and offers both synchronous and asynchronous interfaces for Redis operations.
Key Features of redis-py
The library provides a complete set of functions for working with Redis:
- Support for all Redis data types
- Transactions and pipelines
- Pub/Sub functionality
- Redis Sentinel and cluster support
- Async operations via redis.asyncio
- Connection pooling for performance optimization
- Automatic reconnection on connection drops
Installation and Connection
Installing the Library
pip install redis
To install with additional dependencies:
pip install redis[hiredis] # For improved performance
Connecting to Redis
Basic connection to Redis (default port 6379):
import redis
# Connect to local Redis
client = redis.Redis(host='localhost', port=6379, db=0)
# Connect with password
client = redis.Redis(host='localhost', port=6379, password='yourpassword', db=0)
# Connect via URL
client = redis.from_url('redis://localhost:6379/0')
Testing the Connection
try:
response = client.ping()
print(f"Connection established: {response}") # True
except redis.ConnectionError:
print("Failed to connect to Redis")
Redis Basics and Key Data Types
Redis supports five main data types, each with its own features and methods:
Strings
The most basic Redis data type. Can store text, numbers, and binary data.
Lists
Ordered collections of strings. Support adding elements to the beginning and end.
Sets
Unordered collections of unique strings. Support intersection and union operations.
Hashes
Maps between string fields and values. Ideal for representing objects.
Sorted Sets
Sets with a score for each element. Elements are ordered by score.
Basic Redis Commands via redis-py
Working with Strings
# Set and get a value
client.set("user:name", "John")
name = client.get("user:name").decode('utf-8')
# Set with TTL
client.setex("session:123", 3600, "active") # 1 hour
# Working with numbers
client.set("counter", 0)
client.incr("counter") # Increment by 1
client.incrby("counter", 5) # Increment by 5
client.decr("counter") # Decrement by 1
Working with Lists
# Adding elements
client.lpush("tasks", "task1", "task2") # To the beginning
client.rpush("tasks", "task3", "task4") # To the end
# Retrieving elements
tasks = client.lrange("tasks", 0, -1) # All elements
first_task = client.lpop("tasks") # Remove and return first
last_task = client.