Start learning free

LESSON 60 OF 66 · NOSQL: REDIS

Keys That Expire

Practice

Some data should only live for a while: a login code, a password reset link, a cart nobody comes back to. Redis can remove a key by itself after a number of seconds: you give the key an expiry, a timer. In this lesson your code talks to an in-memory Redis. The same code runs unchanged on a real Redis server.

Timers: add ex= to r.set to store a key with a timer, in seconds. r.ttl(key) (time to live) gives back the seconds left. It gives -1 for a key with no timer and -2 for a key that isn't there. r.expire(key, seconds) puts a timer on a key that already exists, without changing its value.

r.set("reset:bob", "x7k2", ex=600)
print(r.ttl("reset:bob"))   # 600
r.set("theme", "dark")
print(r.ttl("theme"))       # -1: no timer
print(r.ttl("nothing"))     # -2: no such key
r.expire("theme", 30)
print(r.ttl("theme"))       # 30

The starting code stores Ana's cart under "cart:ana" with no timer. After your lines, the check moves the clock 61 seconds forward and reads the keys again, so you never have to wait. The whole output must be:

Code: 482913
Code TTL: 60
Cart TTL: -1
Cart TTL now: 1800
61 seconds later:
Code: None
Code TTL: -2
Cart TTL: 1739

Your task: store Ana's login code "482913" under "login:ana" for 60 seconds, print it and its time left, print the cart's time left, then give the cart 1800 seconds with r.expire and print its time left again.


Assignment
Follow the Coding Tutorial to give keys a timer with ex= and r.expire, and to read the time left with r.ttl.


Hint
ex=60 goes after the value in r.set. From r.ttl, -1 means "there, but no timer" and -2 means "not there at all".


STEP 1 OF 6
    Ctrl + Enter to check