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? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
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
|
Beta Was this translation helpful? Give feedback.
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():