Your destination for complete Tech news

How to store session data in Redis?

29 0
< 1 min read

You can store session data in Redis by using a combination of keys, hashes, and expiry times.

A common way to store session data in Redis is to use a unique key for each session, with the session data stored as a hash. For example, if you’re using a session ID of “abc123” to identify a user’s session, you could store the session data in Redis using the following command:

HMSET session:abc123 user_id 123 name "John Doe" age 30

To retrieve the session data, you can use the “HGETALL” command:

HGETALL session:abc123

This will return all the fields and values in the hash as a dictionary.

You can also set an expiration time for the key using the “EXPIRE” command, to automatically delete the key after a certain amount of time.

EXPIRE session:abc123 1800

This will expire the key in 30 minutes (1800 seconds).

You can also use redis-py library to handle session data in Redis.

import redis
r = redis.Redis(host='localhost', port=6379, db=0)
session_data = {"user_id": 123, "name": "John Doe", "age": 30}
r.hmset("session:abc123", session_data)
r.expire("session:abc123", 1800)

Leave A Reply

Your email address will not be published.

two × five =

This site uses Akismet to reduce spam. Learn how your comment data is processed.