1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 import tornado.web 5 container = {} 6 7 class Session: 8 def __init__(self, handler): 9 self.handler = handler10 self.random_str = None11 12 # 创建随机字符串13 def __genarate_random_str(self):14 import hashlib15 import time16 obj = hashlib.md5()17 obj.update(bytes(str(time.time()), encoding='utf-8'))18 random_str = obj.hexdigest()19 return random_str20 21 def __getitem__(self, item):22 return self.get_value(item)23 24 def get_value(self, key):25 # 获取客户端的随机字符串26 # 从container中获取专属于我的数据27 # 专属信息【key】28 random_str = self.handler.get_cookie("__kakaka__")29 if not random_str:30 return None31 # 客户端有随机字符串32 user_info_dict = container.get(random_str, None)33 if not user_info_dict:34 return None35 value = user_info_dict.get(key,None)36 return value37 38 def __setitem__(self, key, value):39 self.set_value(key,value)40 41 def set_value(self, key, value):42 # 在container中加入随机字符串43 # 定义专属于自己的数据44 # 在客户端中希尔随机字符串45 # 判断,请求的用户名是否已有随机字符串46 if not self.random_str:47 random_str = self.handler.get_cookie('__kakaka__')48 if not random_str:49 random_str = self.__genarate_random_str()50 container[random_str] = {}51 else:52 if random_str in container.keys():53 pass54 else:55 random_str = self.__genarate_random_str()56 container[random_str] = {}57 self.random_str = random_str58 container[self.random_str][key] = value59 self.handler.set_cookie("__kakaka__",self.random_str)
class BaseHandler(tornado.web.RequestHandler): def initialize(self): self.session = session.Session(self)class LoginHandler(BaseHandler): def get(self): if self.get_argument('u',None) in ['alex','eric']: self.session['is_login']=True self.session['name']= self.get_argument('u',None) self.write('已登录') else: self.write('请登录')class ManagerHandler(BaseHandler): def get(self): val = self.session['is_login'] if val: name = self.session['name'] self.write('成功登录,'+name) else: self.write('失败')