![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
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 = handler 10 self.random_str = None 11 12 # 创建随机字符串 13 def __genarate_random_str(self): 14 import hashlib 15 import time 16 obj = hashlib.md5() 17 obj.update(bytes(str(time.time()), encoding='utf-8')) 18 random_str = obj.hexdigest() 19 return random_str 20 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 None 31 # 客户端有随机字符串 32 user_info_dict = container.get(random_str, None) 33 if not user_info_dict: 34 return None 35 value = user_info_dict.get(key,None) 36 return value 37 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 pass 54 else: 55 random_str = self.__genarate_random_str() 56 container[random_str] = {} 57 self.random_str = random_str 58 container[self.random_str][key] = value 59 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('失败')