python全棧系列之---cookie模擬登陸和模擬session原理
阿新 • • 發佈:2018-03-08
ger -c AD log print imp 數據庫 sta 這一
cookie模擬登陸:
import tornado.web class IndexHandler(tornado.web.RequestHandler): def get(self): #self.write("Hello world") # 展示所有的cookie # print(self.cookies) # print(self.get_cookie(‘k1‘)) # self.set_cookie(‘k1‘,‘999‘)#還有 過期時間 適用路徑 # 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(‘請登錄‘) class ManagerHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): #默認self.get_secure_cookie(‘user‘,None)獲取的數據是bytes類型 if str(self.get_secure_cookie(‘user‘,None),encoding="utf8") in [‘asd‘,‘zxc‘]: self.write("歡迎登錄:"+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",IndexHandler), (r"/manager",ManagerHandler), ],**settings) if __name__=="__main__": application.listen(8080) tornado.ioloop.IOLoop.instance().start()View Code
session原理模擬(放在內存),更多是放在Redis,文件,數據庫中
import tornado.web #放在內存 redis 文件 數據庫 container={} class IndexHandler(tornado.web.RequestHandler): def get(self): if self.get_argument(‘u‘,None) in [‘asd‘,‘zxc‘]: import hashlib import time obj = hashlib.md5() obj.update(bytes(str(time.time()),encoding="utf8")) random_str = obj.hexdigest() #這一段隨機字符串需要傳入到客戶端cookie中,以便用戶到服務端對應 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("請登錄") class ManagerHandler(tornado.web.RequestHandler): 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‘]: # 或者container.get(random_str,None) self.write("歡迎登錄" + container[random_str][‘k2‘]) return; self.redirect("/index") settings ={ ‘template_path‘:‘views‘, ‘static_path‘:‘statics‘, ‘cookie_secret‘:‘dafawafawfaw‘, } 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全棧系列之---cookie模擬登陸和模擬session原理