首页 > 代码库 > 自定义Session
自定义Session
#!/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 set_value(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 get_value(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 IndexHander(tornado.web.RequestHandler): def get(self, *args, **kwargs): if self.get_argument(‘u‘,None)in[‘alex‘,‘eric‘]: s = Session(self) s.set_value(‘is_login‘, True) s.set_value(‘name‘, self.get_argument(‘u‘,None)) print(container) else: self.write(‘请登录‘) class ManagerHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): s = Session(self) val = s.get_value(‘is_login‘) if val: self.write(s.get_value(‘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()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div>首页</div> </body> </html>
自定义Session
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。