0
0
RedisHow-ToBeginner · 4 min read

How to Use Redis Cache in Python: Simple Guide

To use Redis cache in Python, install the redis library, connect to the Redis server using redis.Redis(), then use commands like set() and get() to store and retrieve cached data. This allows fast access to frequently used data by storing it in memory.
📐

Syntax

First, import the redis library and create a Redis client connection. Use set(key, value) to store data and get(key) to retrieve it. The data is stored as bytes, so decode it when reading.

python
import redis

# Connect to Redis server (default localhost:6379)
r = redis.Redis(host='localhost', port=6379, db=0)

# Set a key-value pair
r.set('mykey', 'myvalue')

# Get the value by key
value = r.get('mykey')
if value:
    print(value.decode('utf-8'))
Output
myvalue
💻

Example

This example shows how to connect to Redis, cache a value, and retrieve it. It demonstrates storing a string and reading it back with decoding.

python
import redis

# Create Redis client
cache = redis.Redis(host='localhost', port=6379, db=0)

# Cache a value
cache.set('username', 'alice')

# Retrieve cached value
cached_username = cache.get('username')
if cached_username:
    print('Cached username:', cached_username.decode('utf-8'))
else:
    print('No cached value found')
Output
Cached username: alice
⚠️

Common Pitfalls

Common mistakes include not decoding bytes returned by get(), forgetting to run the Redis server, or using wrong connection parameters. Also, storing complex data requires serialization (e.g., JSON) before caching.

python
import redis
import json

r = redis.Redis()

# Wrong: storing dict directly (will cause error)
# r.set('user', {'name': 'bob'})

# Right: serialize dict to JSON string before storing
user_data = {'name': 'bob'}
r.set('user', json.dumps(user_data))

# Retrieve and deserialize
user_json = r.get('user')
if user_json:
    user = json.loads(user_json.decode('utf-8'))
    print(user)
Output
{'name': 'bob'}
📊

Quick Reference

CommandDescription
redis.Redis(host, port, db)Create Redis client connection
set(key, value)Store value in cache under key
get(key)Retrieve value by key (returns bytes or None)
delete(key)Remove key and its value from cache
expire(key, seconds)Set expiration time for a key

Key Takeaways

Install and import the redis Python library to interact with Redis cache.
Use redis.Redis() to connect to the Redis server before caching data.
Store data with set() and retrieve with get(), decoding bytes to strings.
Serialize complex data (like dictionaries) before caching using JSON.
Ensure the Redis server is running and connection parameters are correct.