How to Use Redis in Python: Simple Guide with Examples
To use
redis in Python, install the redis package with pip install redis, then create a Redis client using redis.Redis(). Use this client to set and get data with methods like set() and get().Syntax
First, import the redis library. Then create a Redis client object with redis.Redis(), which connects to the Redis server. Use set(key, value) to store data and get(key) to retrieve it.
python
import redis # Connect to Redis server on localhost and default port r = redis.Redis(host='localhost', port=6379, db=0) # Set a key-value pair r.set('name', 'Alice') # Get the value for a key value = r.get('name') print(value) # Outputs: b'Alice'
Output
b'Alice'
Example
This example shows how to connect to Redis, store a string, and retrieve it. It demonstrates basic usage of the redis Python client.
python
import redis # Create Redis client client = redis.Redis(host='localhost', port=6379, db=0) # Store a value client.set('greeting', 'Hello, Redis!') # Retrieve and decode the value result = client.get('greeting') if result: print(result.decode('utf-8')) else: print('Key not found')
Output
Hello, Redis!
Common Pitfalls
- Not running the Redis server before connecting causes connection errors.
- Forgetting to decode bytes returned by
get()leads to confusing output. - Using wrong host or port will fail to connect.
- Not handling missing keys can cause
NoneTypeerrors.
python
import redis r = redis.Redis() # Wrong way: directly printing get() result without decoding value = r.get('missing_key') print(value) # Prints None or bytes, not user-friendly # Right way: check and decode if value: print(value.decode('utf-8')) else: print('Key not found')
Output
None
Key not found
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 for a key (returns bytes or None) |
| delete(key) | Remove a key from Redis |
| exists(key) | Check if a key exists (returns 1 or 0) |
Key Takeaways
Install the redis Python package and run the Redis server before connecting.
Use redis.Redis() to create a client and connect to your Redis server.
Store data with set() and retrieve with get(), decoding bytes to strings.
Always check if a key exists or if get() returns None to avoid errors.
Use the quick reference table to remember common Redis commands in Python.