Session_expire = 60
Session_type = ' Redis '
Pool = Redis. ConnectionPool (host="localhost", port=6379) Redi_conn= Redis. Redis (connection_pool=pool)classbasesession: @classmethod def get_session_handler (cls,handler):ifConfig. Session_type = ="Memery": obj=memerysession (handler) elif config. Session_type=="Mamcache": obj=memcachesession (handler) elif config. Session_type=="Redis": obj=redissession (handler)returnobjclassredissession:session_id="py_session"def __init__ (self,handler): Self.handler=handler #从客户端获取随机字符串 client_random_str=Self.handler.get_cookie (memcachesession.session_id) #如果获取到了字符串ifClient_random_str and Redi_conn.exists (CLIENT_RANDOM_STR): Self.random_str=Client_random_strElse: Self.random_str=self.__genarate_random_str () redi_conn.hset (Self.random_str,none,none) Redi_conn.expire (self.random _str,config. Session_expire) Expires_time= Time.time () +CONFIG. Session_expire Handler.set_cookie (MEMERYSESSION.PREX_STR, SELF.RANDOM_STR, expires=expires_time) def __setitem__ (self, Key, value): Redi_conn.hget (Self.random_str,key) Redi_conn.hset (s Elf.random_str, Key,value) redi_conn.expire (self.random_str, config. Session_expire) def __getitem__ (self, item): RET=redi_conn.hget (Self.random_str,item)returnret def __delitem__ (self, Key): Redi_conn.hdel (Self.random_str,key) Redi_conn.expire (self.random_str , CONFIG. Session_expire) def __genarate_random_str (self): obj=hashlib.md5 () obj.update (bytes (str (time.time ()), encoding="UTF8")) Random_str=obj.hexdigest ()returnRandom_str
Attention:
Get data type bytes in 1.redis, type conversion is required for comparisons such as CAPTCHA comparisons
if str (self.session['code'].lower (), encoding="UTF8" )! = self.get_argument ('code'). Lower (): status[' Status'] = False status['error'" Verification Code Error "
Or convert the accepted data to the bytes type
2. Store the data if other types
Needs to be performed using eval when used, which is the original string to the data type
Python---A custom session for Redis