python---redis实现自定义session

SESSION_EXPIRE = 60
SESSION_TYPE = 'Redis'


pool = redis.ConnectionPool(host="localhost",port=6379) redi_conn = redis.Redis(connection_pool=pool) class BaseSession: @classmethod def get_session_handler(cls,handler): if config.SESSION_TYPE == "Memery": obj = MemerySession(handler) elif config.SESSION_TYPE == "Mamcache": obj = MemcacheSession(handler) elif config.SESSION_TYPE == "Redis": obj = RedisSession(handler) return obj class RedisSession: session_id = "py_session" def __init__(self,handler): self.handler = handler #从客户端获取随机字符串 client_random_str = self.handler.get_cookie(MemcacheSession.session_id) #如果获取到了字符串 if client_random_str and redi_conn.exists(client_random_str): self.random_str = client_random_str else: 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(self.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) return ret 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() return random_str

注意:

1.redis中获取数据类型为bytes,在进行比较,例如验证码比较时,需要进行类型转换

      if str(self.session['code'].lower(),encoding="utf8") != self.get_argument('code').lower():
                status['status'] = False
                status['error'] = "验证码错误"

或者将接受的数据转换为bytes类型

2.存放数据如果为其他类型

需要在使用时使用eval执行,是原来字符串转为数据类型

posted @ 2018-03-20 19:54  山上有风景  阅读(1260)  评论(0编辑  收藏  举报