python---基于memcache的自定义session类
import config import hashlib import time import memcache import json conn = memcache.Client(["127.0.0.1:8081"],debug=True) 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 MemcacheSession: 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 conn.get(client_random_str): self.random_str = client_random_str else: self.random_str = self.__genarate_random_str() conn.set(self.random_str,json.dumps({}),config.SESSION_EXPIRE) conn.set(self.random_str,conn.get(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): ret = conn.get(self.random_str) ret_dict = json.loads(ret) ret_dict[key]=value conn.set(self.random_str, json.dumps(ret_dict), config.SESSION_EXPIRE) def __getitem__(self, item): ret = conn.get(self.random_str) ret_dict = json.loads(ret) return ret_dict.get(item,None) def __delitem__(self, key): ret = conn.get(self.random_str) ret_dict = json.loads(ret) del ret_dict[key] conn.set(self.random_str, json.dumps(ret_dict), 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