Cookie Emulation Login:
Import Tornado.webclass Indexhandler (tornado.web.RequestHandler): Def get (self): #self. Write ("Hello World") # Show All Cookies # print (self.cookies) # Print (Self.get_cookie (' K1 ')) # Self.set_cookie (' K1 ', ' 999 ') #还 There is an expiration time for the path # self.render ("index.html") If Self.get_argument (' U ', None) in [' ASD ', ' zxc ']: Self.set _secure_cookie (' User ', self.get_argument (' U ')) else:self.write (' Please login ') class Managerhandler (tornado.web.Re Questhandler): Def get (self, *args, **kwargs): #默认self. Get_secure_cookie (' user ', None) Gets the data is bytes type if str (Self.get_secure_cookie (' user ', None), encoding= "UTF8") in [' ASD ', ' zxc ']: Self.write ("Welcome to login:" +str (self.get_secure_ Cookie (' user '), encoding= "UTF8")) else:self.redirect ('/index ') settings ={' Template_path ': ' Views ', ' Static_path ': ' statics ', ' cookie_secret ': ' dafawafawfaw ',}application = Tornado.web.Application ([R '/index ', indexh Andler), (R "/manager",Managerhandler),],**settings) if __name__== "__main__": Application.listen (8080) tornado.ioloop.IOLoop.instance (). Start ()
View Code
Session principle Simulation (put in memory), more is placed in Redis, file, database
Import tornado.web# is placed in the memory Redis file database Container={}class Indexhandler (tornado.web.RequestHandler): Def get (self): If self.get_argument (' U ', None) in [' ASD ', ' ZXC ']: Import hashlib import Time obj = Hashli B.MD5 () obj.update (bytes (str (time.time ()), encoding= "UTF8")) Random_str = Obj.hexdigest () #这一段随机字符串需要传入到客户端cookie中, so that the user to the server corresponds to container[random_str]={} container[random_str][' K1 ']=123 container[random_str][' K2 ']=self.get_argument (' u ') + ' parents ' container[random_str][' Is_login ']=True Self.set_cookie (' py_session ', random_str) else:self.write ("Please login") class Managerhandler (Tornado.web.Req Uesthandler): Def get (self, *args, **kwargs): Random_str = Self.get_cookie (' py_session ', None) if random_ Str:if Container.get (random_str,none): If container[random_str][' Is_login ']: # or Container.get (Random_str,none) Self.write ("Welcome login" + container[random_str][' K2 ') return; Self.redirect ("/index") settings ={' Template_path ': ' Views ', ' static_path ': ' statics ', ' cookie_secret ': ' DAFAWAFAWFA W ',}application = Tornado.web.Application ([r "/index", Indexhandler), (R "/manager", Managerhandler),],**settings) if __name__== "__main__": Application.listen (8080) tornado.ioloop.IOLoop.instance (). Start ()
View Code
Python Full Stack---Cookie simulation login and simulation session principle