session.py插件
# coding:utf8
# __author: Administrator
# date: //
# /usr/bin/env python
import config
import hashlib
import time class BaseSession:
@classmethod
def get_session_handler(cls,handler):
if config.SESSION_TYPE == "Memery":
obj = MemerySession(handler)
return obj class MemerySession:
container = {}
prex_str="py_session" def __init__(self,handler):
self.handler = handler
client_random_str = handler.get_cookie(MemerySession.prex_str,None)
if client_random_str and client_random_str in MemerySession.container:
self.random_str=client_random_str
else:
self.random_str = self.__genarate_random_str()
MemerySession.container[self.random_str]={}
expires_time = time.time() + config.SESSION_EXPIRE
handler.set_cookie(MemerySession.prex_str,self.random_str,expires=expires_time) def __genarate_random_str(self):
obj = hashlib.md5()
obj.update(bytes(str(time.time()),encoding="utf8"))
random_str=obj.hexdigest()
return random_str def __setitem__(self, key, value):
MemerySession.container[self.random_str][key]=value def __getitem__(self, key):
ret = MemerySession.container[self.random_str].get(key, None)
return ret class RedisSession:
pass class FileSession:
pass class MysqlSession:
pass
在公共控制类中引入
import tornado.web
from backend.session.session import BaseSession class BaseRequestHandler(tornado.web.RequestHandler):
def initialize(self):
self.session = BaseSession.get_session_handler(self)
在控制类中使用
class LoginHandler(BaseRequestHandler):
def get(self):
pass def post(self):
#验证成功,缓存信息
self.session['username'] = ret.username
self.session['email'] = ret.email