0
0
Redisquery~5 mins

Redis with Python (redis-py)

Choose your learning style9 modes available
Introduction

Redis is a fast database that stores data in memory. Using Python with Redis lets you quickly save and get data in your programs.

You want to cache data to make your app faster.
You need to store user sessions for a website.
You want to count things like page views in real time.
You want to share data between different parts of your app quickly.
You want to store simple key-value pairs without complex setup.
Syntax
Redis
import redis

r = redis.Redis(host='localhost', port=6379, db=0)
r.set('key', 'value')
value = r.get('key')
Use redis.Redis() to connect to your Redis server.
Use set() to save data and get() to retrieve it.
Examples
Saves the name 'Alice' and then gets it back.
Redis
r.set('name', 'Alice')
print(r.get('name'))
Saves a number 10 as a string and retrieves it.
Redis
r.set('count', 10)
print(r.get('count'))
Deletes the key 'name' and tries to get it, which returns None.
Redis
r.delete('name')
print(r.get('name'))
Sample Program

This program connects to Redis, saves the color 'blue', then gets and prints it.

Redis
import redis

r = redis.Redis(host='localhost', port=6379, db=0)
r.set('color', 'blue')
value = r.get('color')
print(value.decode('utf-8'))
OutputSuccess
Important Notes

Redis stores data as bytes, so use decode('utf-8') to convert to string.

Make sure Redis server is running before connecting.

Use r.delete('key') to remove data.

Summary

Redis with Python lets you store and get data fast using simple commands.

Use set() to save and get() to retrieve data.

Remember to decode bytes to strings when reading data.