首页 > 代码库 > python tornado 自定义session

python tornado 自定义session

python tornado 中需要自定session

session原理:

  1.客户端发送请求信息,服务端为用户端生成一个加密随机字符串random_str,然后将用户的信息作为这个随机字符串random_str的值,增加用户信息的安全性;

  2.将random_str做为cookie写入给客户端,然后服务端进行判断用户携带cookie的情况

 

技术分享
 1 import tornado.web
 2 import tornado.ioloop
 3 
 4 class Session():
 5     def __init__(self,handler):
 6         self.random_str = None
 7         self.handler = handler
 8     def __random_str(self):
 9         ‘‘‘生成随机字符串‘‘‘
10         import hashlib
11         import time
12         obj = hashlib.md5()
13         obj.update(bytes(str(time.time()), encoding=utf-8))
14         random_str = obj.hexdigest()
15         return random_str
16 
17     def __setitem__(self,key,value):
18         ‘‘‘设置用户信息‘‘‘
19         random_str = self.handler.get_cookie(user_cookie)
20         if not self.random_str:
21             if not random_str:
22                 random_str = self.__random_str()
23                 container[random_str]={}
24             else:
25                 if random_str in container.keys():
26                     pass
27                 else:
28                     random_str = self.__random_str()
29                     container[random_str]={}
30             self.random_str = random_str
31         container[self.random_str][key] = value
32         self.handler.set_cookie(user_cookie,self.random_str)
33     def __getitem__(self,key):
34         ‘‘‘获取用户信息‘‘‘
35         random_str = self.handler.get_cookie(user_cookie)
36         if not random_str:
37             return None
38         user_info_dict = container.get(random_str,None)
39         if not user_info_dict:
40             return None
41         value =http://www.mamicode.com/ user_info_dict.get(key,None)
42         return value
43 container={}
44 class BaseHandler(tornado.web.RequestHandler):
45     def initialize(self):
46         self.session =Session(self)
47 class IndexHandler(BaseHandler):
48     def get(self):
49         if self.get_argument(user,None) in ["jam","nina"]:
50             self.session[is_login] =True
51             self.session[name] = self.get_argument(user,None)
52             self.write(登录成功)
53             self.redirect(/manager)
54         else:
55             self.render(index.html,item = 请登录)
56 
57 class ManagerHandler(BaseHandler):
58     def get(self):
59         val = self.session[is_login]
60         if val:
61             self.write(user:%s%self.session[name])
62         else:
63             self.render(index.html,item=login fail)
64 settings={
65     "template_path":"views",
66 }
67 
68 application = tornado.web.Application([
69     (r/index,IndexHandler),
70     (r/manager,ManagerHandler),
71 ],**settings)
72 
73 if __name__=="__main__":
74     application.listen(8880)
75     tornado.ioloop.IOLoop.instance().start()
session

 

python tornado 自定义session