pool = redis.ConnectionPool(host="localhost",port=6379)
redi_conn= redis.Redis(connection_pool=pool)classBaseSession:
@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)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(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)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()return random_str