How to Use redis-py in Python: Simple Guide with Examples
To use
redis-py in Python, first install it with pip install redis. Then, create a Redis client using redis.Redis(), and use methods like set() and get() to store and retrieve data.Syntax
The basic syntax to use redis-py involves creating a Redis client and calling its methods to interact with the Redis server.
redis.Redis(host, port, db): Connects to Redis server.set(key, value): Stores a value under a key.get(key): Retrieves the value of a key.
python
import redis # Create Redis client r = redis.Redis(host='localhost', port=6379, db=0) # Set a key-value pair r.set('mykey', 'hello') # Get the value of the key value = r.get('mykey') print(value)
Output
b'hello'
Example
This example shows how to connect to Redis, set a key with a string value, and get the value back. It demonstrates basic usage of redis-py.
python
import redis # Connect to Redis server running locally client = redis.Redis(host='localhost', port=6379, db=0) # Store a value client.set('greeting', 'Hello, Redis!') # Retrieve the value result = client.get('greeting') # Print the result decoded to string print(result.decode('utf-8'))
Output
Hello, Redis!
Common Pitfalls
Common mistakes when using redis-py include:
- Not decoding the bytes returned by
get()before printing or using it. - Forgetting to install the
redispackage. - Not running a Redis server locally or not specifying the correct host and port.
- Using wrong data types or forgetting that Redis stores bytes, so conversion is needed.
python
import redis r = redis.Redis() # Wrong: printing raw bytes r.set('key', 'value') print(r.get('key')) # Outputs: b'value' # Right: decode bytes to string print(r.get('key').decode('utf-8')) # Outputs: value
Output
b'value'
value
Quick Reference
| Command | Description |
|---|---|
| redis.Redis(host, port, db) | Create a Redis client connection |
| set(key, value) | Store a value under a key |
| get(key) | Retrieve the value of a key (returns bytes) |
| delete(key) | Remove a key from Redis |
| exists(key) | Check if a key exists (returns 1 or 0) |
Key Takeaways
Install redis-py with pip before using it in Python.
Create a Redis client with redis.Redis() specifying host and port.
Use set() to store data and get() to retrieve data from Redis.
Remember to decode bytes returned by get() to use as strings.
Ensure Redis server is running and accessible at the specified host and port.