Using Redis with Python for Data Storage and Retrieval
This article explains how to install and configure Redis, connect to it using Python's redis library, and demonstrates storing and retrieving various data structures—including strings, hashes, lists, sets, and sorted sets—followed by proper disconnection, providing a practical guide for Python developers.
Redis is an in‑memory key‑value database that supports multiple data structures such as strings, hashes, lists, sets and sorted sets. Using Redis with Python provides a high‑performance caching and storage solution.
1. Install and configure Redis – Install Redis on the server, ensure the Redis service is running, and install the Python redis library in your environment.
2. Connect to Redis – Create a Redis client instance with the host and port of the Redis server.
import redis
redis_client = redis.Redis(host='127.0.0.1', port=6379)3. Store and retrieve data – Use Redis commands to manipulate different data types.
String:
redis_client.set('key', 'value')
value = redis_client.get('key')Hash:
redis_client.hset('hash', 'field', 'value')
value = redis_client.hget('hash', 'field')List:
redis_client.lpush('list', 'value1')
redis_client.lpush('list', 'value2')
values = redis_client.lrange('list', 0, -1)Set:
redis_client.sadd('set', 'value1')
redis_client.sadd('set', 'value2')
values = redis_client.smembers('set')Sorted set:
redis_client.zadd('sorted_set', {'value1': 1, 'value2': 2})
values = redis_client.zrange('sorted_set', 0, -1)4. Disconnect – Close the client when operations are finished. redis_client.close() These steps enable Python applications to use Redis for caching, session management, leaderboards, queues and other scenarios by selecting appropriate data structures and commands.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
