1. 程式人生 > >第二百六十九節,Tornado框架-Session登錄判斷

第二百六十九節,Tornado框架-Session登錄判斷

獲取系統當前時間 __main__ 參數 art emp exp 登錄密碼 字典 cnblogs

Tornado框架-Session登錄判斷

Session需要結合cookie來實現

Session的理解

  1、用戶登錄系統時,服務器端獲取系統當前時間,進行nd5加密,得到加密後的密串

  2、將密串作為一個字典的鍵,值為一個字典,也就是嵌套字典,鍵為密串的字典裏保存用戶信息

  3、將這個密串當做cookie值寫入瀏覽器

  4、當用戶訪問時,判斷值為密串的cookie是否存在,如果存在,獲取cookie的值也就是密串,將這個密串在服務端的字典裏查找是否存在,如果存在就可以拿到用戶保存的各種信息,判斷用戶是否是登錄狀態

技術分享

框架引擎

#!/usr/bin/env python
#
coding:utf-8 import tornado.ioloop import tornado.web #導入tornado模塊下的web文件 container = {} #用戶登錄信息字典,保存著用戶的登錄信息,{‘328eb994f73b89c5f1de57742be1ee82‘: {‘is_login‘: True, ‘mim‘: ‘admin‘, ‘yhm‘: ‘admin‘}} class indexHandler(tornado.web.RequestHandler): #
定義一個類,繼承tornado.web下的RequestHandler類 def get(self): #get()方法,接收get方式請求 hq_cookie = self.get_cookie(xr_cookie) #獲取瀏覽器cookie session = container.get(hq_cookie,None) #將獲取到的cookie值作為下標,在數據字典裏找到對應的用戶信息字典 if
not session: #判斷用戶信息不存在 self.redirect("/dlu") # 顯示登錄html文件 #跳轉到登錄頁面 else: if session.get(is_login,None) == True: #否則判斷用戶信息字典裏的下標is_login是否等於True self.render("index.html") # 顯示index.html文件 #顯示查看頁面 else: self.redirect("/dlu")
#跳轉登錄頁面 class dluHandler(tornado.web.RequestHandler): def get(self): hq_cookie = self.get_cookie(xr_cookie) #獲取瀏覽器cookie session = container.get(hq_cookie,None) #將獲取到的cookie值作為下標,在數據字典裏找到對應的用戶信息字典 if not session: #判斷用戶信息不存在 self.render("dlu.html") # 顯示登錄html文件 #打開到登錄頁面 else: if session.get(is_login,None) == True: #否則判斷用戶信息字典裏的下標is_login是否等於True self.redirect("/index") # 顯示index.html文件 #跳轉查看頁面 else: self.redirect("/dlu") #跳轉登錄頁面 def post(self): yhm = self.get_argument(yhm) #接收用戶輸入的登錄賬號 mim = self.get_argument(mim) #接收用戶輸入的登錄密碼 if yhm == admin and mim == admin: #判斷用戶的密碼和賬號 import hashlib #導入md5加密模塊 import time #導入時間模塊 obj = hashlib.md5() #創建md5加密對象 obj.update(bytes(str(time.time()),encoding = "utf-8")) #獲取系統當前時間,傳入到md5加密對象裏加密 suijishu = obj.hexdigest() #獲取加密後的密串 container[suijishu] = {} #將密串作為下標到container字典裏,創建一個新空字典 container[suijishu][yhm] = yhm #字典裏的鍵為yhm,值為用戶名 container[suijishu][mim] = mim #字典裏的鍵為mim,值為用戶密碼 container[suijishu][is_login] = True #字典裏的鍵為is_login,值為True self.set_cookie(xr_cookie,suijishu,expires_days=1) #將密串作為cookie值寫入瀏覽器 self.redirect("/index") #跳轉到查看頁面 else: self.redirect("/dlu") settings = { #html文件歸類配置,設置一個字典 "template_path":"views", #鍵為template_path固定的,值為要存放HTML的文件夾名稱 "static_path":"statics", #鍵為static_path固定的,值為要存放js和css的文件夾名稱 "cookie_secret":"61oETzKXQAGaYdkL5gEmGeJJY", } #路由映射 application = tornado.web.Application([ #創建一個變量等於tornado.web下的Application方法 (r"/index", indexHandler), #判斷用戶請求路徑後綴是否匹配字符串index,如果匹配執行MainHandler方法 (r"/dlu", dluHandler), ],**settings) #將html文件歸類配置字典,寫在路由映射的第二個參數裏 if __name__ == "__main__": #內部socket運行起來 application.listen(8888) #設置端口 tornado.ioloop.IOLoop.instance().start()

第二百六十九節,Tornado框架-Session登錄判斷