Databases 7 min read

Master Redis with Python: 10 Essential Operations and Code Samples

This guide walks through ten common Redis tasks—setting and getting keys, deleting keys, listing keys, hash, list, set, sorted‑set operations, publish/subscribe, pipeline, and transactions—each illustrated with clear Python redis‑py code examples.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Master Redis with Python: 10 Essential Operations and Code Samples

1. Set and Get a Key

Demonstrates how to store a value under a key and retrieve it using the redis Python client.

import redis

def set_and_get_key(key, value):
    r = redis.Redis(host='localhost', port=6379, db=0)
    r.set(key, value)
    return r.get(key).decode('utf-8')

if __name__ == "__main__":
    key = "example_key"
    value = "example_value"
    print(set_and_get_key(key, value))

2. Delete a Key

Shows how to remove a specific key‑value pair from Redis.

import redis

def delete_key(key):
    r = redis.Redis(host='localhost', port=6379, db=0)
    r.delete(key)

if __name__ == "__main__":
    key = "example_key"
    delete_key(key)

3. List All Keys

Retrieves and prints every key currently stored in the selected database.

import redis

def list_all_keys():
    r = redis.Redis(host='localhost', port=6379, db=0)
    keys = r.keys()
    return [key.decode('utf-8') for key in keys]

if __name__ == "__main__":
    print(list_all_keys())

4. Hash Table Operations

Uses a Redis hash to store a composite object, setting a field and then reading it back.

import redis

def hash_operations(key, field, value):
    r = redis.Redis(host='localhost', port=6379, db=0)
    r.hset(key, field, value)
    return r.hget(key, field).decode('utf-8')

if __name__ == "__main__":
    key = "user:1"
    field = "name"
    value = "John Doe"
    print(hash_operations(key, field, value))

5. List Operations

Illustrates how to push an element onto a Redis list and read all elements.

import redis

def list_operations(key, value):
    r = redis.Redis(host='localhost', port=6379, db=0)
    r.rpush(key, value)
    return r.lrange(key, 0, -1)

if __name__ == "__main__":
    key = "my_list"
    value = "item1"
    items = list_operations(key, value)
    for item in items:
        print(item.decode('utf-8'))

6. Set Operations

Shows how to add a member to a Redis set and retrieve all unique members.

import redis

def set_operations(key, member):
    r = redis.Redis(host='localhost', port=6379, db=0)
    r.sadd(key, member)
    return r.smembers(key)

if __name__ == "__main__":
    key = "my_set"
    member = "item1"
    members = set_operations(key, member)
    for member in members:
        print(member.decode('utf-8'))

7. Sorted Set Operations

Stores elements with an associated score, then retrieves them in order with scores.

import redis

def sorted_set_operations(key, member, score):
    r = redis.Redis(host='localhost', port=6379, db=0)
    r.zadd(key, {member: score})
    return r.zrange(key, 0, -1, withscores=True)

if __name__ == "__main__":
    key = "my_sorted_set"
    member = "item1"
    score = 10.0
    items = sorted_set_operations(key, member, score)
    for item, score in items:
        print(f"{item.decode('utf-8')} with score {score}")

8. Publish and Subscribe

Demonstrates a simple pub/sub pattern where one thread listens on a channel while another publishes a message.

import redis
import threading
import time

def publish_message(channel, message):
    r = redis.Redis(host='localhost', port=6379, db=0)
    r.publish(channel, message)

def subscribe_to_channel(channel):
    r = redis.Redis(host='localhost', port=6379, db=0)
    pubsub = r.pubsub()
    pubsub.subscribe(channel)
    for item in pubsub.listen():
        if item['type'] == 'message':
            print(f"Received message: {item['data'].decode('utf-8')}")

if __name__ == "__main__":
    channel = "test_channel"
    message = "Hello, world!"
    subscriber_thread = threading.Thread(target=subscribe_to_channel, args=(channel,))
    subscriber_thread.start()
    time.sleep(1)
    publish_message(channel, message)

9. Use Pipeline to Reduce Round‑Trips

Shows how to batch multiple commands in a pipeline, cutting down network latency.

import redis

def pipeline_operations(key, value):
    r = redis.Redis(host='localhost', port=6379, db=0)
    pipe = r.pipeline()
    pipe.set(key, value)
    pipe.get(key)
    results = pipe.execute()
    return results[1].decode('utf-8')

if __name__ == "__main__":
    key = "pipeline_key"
    value = "pipeline_value"
    print(pipeline_operations(key, value))

10. Use Transactions for Atomicity

Wraps a set and get operation in a Redis transaction to guarantee they execute as an indivisible unit.

import redis

def transaction_operations(key, value):
    r = redis.Redis(host='localhost', port=6379, db=0)
    pipe = r.pipeline(transaction=True)
    pipe.multi()
    pipe.set(key, value)
    pipe.get(key)
    results = pipe.execute()
    return results[1].decode('utf-8')

if __name__ == "__main__":
    key = "transaction_key"
    value = "transaction_value"
    print(transaction_operations(key, value))
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

CachePythondatabaseredisTutorialRedis-py
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.