Python operation Redis setting key expiration time instance code, pythonredis
The Expire command is used to set the key expiration time. The key is no longer available after it expires.
R. set ('2', '4028b2883d3f5a8b013d57228d760a93 ') # if the result is successful, True is returned and False is returned. The following 20 indicates 20 seconds of print r. expire ('2', 20) # if the time is not valid, we can get the value of key 2, or Noneprint r. get ('2 ')
For an existing key, we can set its expiration time. At that time, when you access the key again, the key does not exist.
There are two ways to set the expiration time. One is to specify how long the key can survive from the current time. The unit of time is two, one is second and the other is millisecond.
The second method is to specify that the key is invalid at a certain time. This requires specifying the year, month, day, hour, minute, and second. If the specified time is earlier than the current time, the key will immediately become invalid.
Now, we add two keys in redis: ex1 and ex2.
Set the expiration time in two different ways.
# coding=utf-8 ''' Created on 2015-9-8 @author: kwsy ''' import redis import datetime import time pool=redis.ConnectionPool(host='192.168.1.126',port=6379,db=0) r = redis.StrictRedis(connection_pool=pool) extime = datetime.datetime(2015,9,8,15,19,10) print r.expire('ex1', 10) print extime.strftime('%Y-%m-%d %H:%M:%S %f') print r.expireat('ex2', extime)
The expire function sets the expiration time to 10 seconds. Ex1 will expire in 10 seconds
Expireat sets a specific time. After this time, ex2 will expire at, January 1, September 8.
If the expiration time is set successfully, True is returned. Otherwise, False is returned.
Summary
The above is all about the code for setting the key expiration time for Python operations on Redis instances. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!