Tornado自定义Session
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#!/usr/bin/env python import tornado.ioloop import tornado.web container = {} class Session: def __init__(self,handler): self.handler = handler self.random_str = None def __set_random_str(self): import hashlib import time obj = hashlib.md5 ( ) obj.update ( bytes ( str ( time.time ( ) ), encoding='utf-8' ) ) random_str = obj.hexdigest () return random_str def __setitem__(self,key,value): if not self.random_str: random_str = self.handler.get_cookie('__kakaka__') if not random_str: random_str = self.__set_random_str() container[random_str] = {} else: if random_str in container.keys(): pass else: random_str = self.__set_random_str() container[random_str] = {} self.random_str = random_str container[self.random_str][key] = value self.handler.set_cookie("__kakaka__",self.random_str) def __getitem__(self,key): random_str = self.handler.get_cookie('__kakaka__') if not random_str: return None user_info_dict = container.get(random_str,None) if not user_info_dict: return None value = user_info_dict.get(key,None) return value class BaseHandler(tornado.web.RequestHandler): def initialize(self): self.session = Session(self) class IndexHander(BaseHandler): def get(self, *args, **kwargs): if self.get_argument('u',None)in['alex','eric']: self.session['is_login'] = True self.session['name'] = self.get_argument('u',None) else: self.write('请登录') class ManagerHandler(BaseHandler): def get(self, *args, **kwargs): val = self.session['is_login'] if val: self.write(self.session['name']) else: self.write("失败") settings = { "template_path":"views", "static_path":"statics", "cookie_secret":"taochen" } application = tornado.web.Application([ (r"/index",IndexHander), (r"/manager",ManagerHandler), ],**settings) if __name__ == '__main__': application.listen(8888) tornado.ioloop.IOLoop.instance().start()
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div>首页</div> </body> </html>