How to set expiry time on a Redis key using redis-py? #4096
|
I want to store a key-value pair in Redis with an automatic expiry time For example, I want a session token to expire after 30 minutes. What is the correct way to do this using redis-py? |
Replies: 2 comments
|
You can set expiry time in two ways using redis-py: Option 1 — import redis
r = redis.Redis(host='localhost', port=6379, db=0)
# Store key with 30 minute expiry (1800 seconds)
r.setex('session_token', 1800, 'your_token_value')Option 2 — r.set('session_token', 'your_token_value', ex=1800)Option 3 — Set key first, then add expiry with r.set('session_token', 'your_token_value')
r.expire('session_token', 1800) # secondsCheck remaining TTL: ttl = r.ttl('session_token')
print(ttl) # seconds remaining, -1 = no expiry, -2 = key doesn't existFor millisecond precision use r.set('session_token', 'your_token_value')
r.pexpire('session_token', 1800000) # milliseconds
|
|
You can set an expiry time on a Redis key using redis-py in a few ways depending on your use case. Option 1: Set key with expiry in one command using This sets the key and expiry atomically: import redis
r = redis.Redis(host='localhost', port=6379, db=0)
# setex(name, time_in_seconds, value)
r.setex('session_token', 1800, 'abc123xyz') # expires in 30 minutesOption 2: Use The r.set('session_token', 'abc123xyz', ex=1800) # 30 minutes in seconds
r.set('session_token', 'abc123xyz', px=1800000) # 30 minutes in milliseconds
r.set('session_token', 'abc123xyz', exat=1754000000) # specific Unix timestampOption 3: Set expiry separately using If the key already exists and you want to add or update the TTL: r.set('session_token', 'abc123xyz')
r.expire('session_token', 1800) # set TTL to 30 minutesCheck remaining TTL: ttl = r.ttl('session_token')
# returns seconds remaining
# -1 if no expiry set
# -2 if key does not exist
print(ttl)For session tokens, Option 2 with |
You can set expiry time in two ways using redis-py:
Option 1 —
setex()(set + expiry in one call):Option 2 —
set()withexparameter:Option 3 — Set key first, then add expiry with
expire():Check remaining TTL:
For millisecond precision use
pexpire():