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


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()

 

 

Session模塊封裝以及使用

Session(self,1) 創建session對象,參數1接收接收tornado.web.RequestHandler的self對象,也就是繼承RequestHandler對象,參數2cookie過期時間
session['yhm']=yhm 自定義用戶保存數據,保存在字典里['鍵']=值
session['yhm'] 獲取自定義保存的數據,['鍵']

Session封裝模塊

#!/usr/bin/env python #coding:utf-8
 container = {} # container = { # # "第一個人的隨機字符串":{}, # # "第一個人的隨機字符串":{'k1': 111, 'parents': '你'}, # }

class Session: def __init__(self, handler,gqshijian): """ 創建Session()對象時接收兩個參數 參數1、接收RequestHandler的self對象,也就是繼承RequestHandler對象 參數2、接收cookie過期時間天數 """ self.handler = handler                                  #handler接收tornado.web.RequestHandler的self對象,也就是繼承RequestHandler對象
        self.random_str = None                                  #初始化隨機密串
        self.gqshijian = gqshijian                              #獲取設置cookie過期時間

    def __genarate_random_str(self):                            #生成隨機密串
        import hashlib                                          #導入md5加密模塊
        import time                                             #導入時間模塊
        obj = hashlib.md5()                                     #創建md5加密對象
        obj.update(bytes(str(time.time()), encoding='utf-8'))   #獲取系統當前時間,進行md5加密
        random_str = obj.hexdigest()                            #獲取加密后的md5密串
        return random_str                                       #返回加密后的md5密串

    def __setitem__(self, key,value):                                   #當創建Session對象,后面跟着[xxx]=xxx的時候自動執行並且接收[xxx]=xxx的值
        """ 使用方法:Session對象[xxx]=xxx 功能:隨機生成密串寫入cookie,接收自定義用戶數據,添加到cookie密串對應的字典里 """
        # 在container中加入隨機字符串
        # 定義專屬於自己的數據
        # 在客戶端中寫入隨機字符串
        # 判斷,請求的用戶是否已有隨機字符串
        if not self.random_str:                                         #判斷初始化密串不存在
            random_str = self.handler.get_cookie('xr_cookie')          #獲取客服端瀏覽器get_cookie里的密串
            if not random_str:                                          #判斷客服端瀏覽器get_cookie里如果沒有密串
                random_str = self.__genarate_random_str()               #執行密串生成方法,生成密串
                container[random_str] = {}                              #在container字典里添加一個,密串作為鍵,值為空字典的元素
            else:                                                       #如果客服端瀏覽器get_cookie里有密串
                # 客戶端有隨機字符串
                if random_str in container.keys():                      #判斷密串在container字典的鍵里是否存在
                    pass                                                #如果存在什么都不做
                else:                                                   #如果不存在
                    random_str = self.__genarate_random_str()           #重新生成密串
                    container[random_str] = {}                          #在container字典里添加一個,密串作為鍵,值為空字典的元素
            self.random_str = random_str                                #將密串賦值給,初始化密串
        # 如果用戶密串初始化就存在,說明登錄過並且cookie和container字典里都存在
        container[self.random_str][key] = value                                                     #找到container字典里鍵為密串的元素值是一個字典,將接收到的key作為鍵,value作為值添加到元素字典里
        self.handler.set_cookie("xr_cookie", self.random_str,expires_days = self.gqshijian)        #將密串作為cookie值,向瀏覽器寫入cookie

    def __getitem__(self,key):                                          #當創建Session對象,后面跟着[xxx]自動執行,並接收[xxx]的值
        """ 使用方法:Session對象[xxx] 功能:獲取cookie對應字典里,鍵為接收到參數的值,存在返回值,不存在返回None """
        # 獲取客戶端的隨機字符串
        # 從container中獲取專屬於我的數據
        # 專屬信息【key】
        random_str =  self.handler.get_cookie("xr_cookie")             #獲取cookie里的密串
        if not random_str:                                              #判斷cookie里的密串如果不存在
            return None                                                 #返回None
        # 客戶端有隨機字符串
        user_info_dict = container.get(random_str,None)                 #在container字典里找到密串對應的元素
        if not user_info_dict:                                          #如果container字典里沒有密串對應的元素
            return None                                                 #返回None
        #如果cookie里的密串存在,並且container字典里也存在密串對應的元素
        value = user_info_dict.get(key, None)                           #接收用戶傳來的值,將值作為鍵找到字典里對應的值
        return value                                                    #返回值

框架引擎

#!/usr/bin/env python
#coding:utf-8

import tornado.ioloop
import tornado.web                              #導入tornado模塊下的web文件
import session_lei                              #導入session模塊




class indexHandler(tornado.web.RequestHandler):  #定義一個類,繼承tornado.web下的RequestHandler類
    def get(self):                               #get()方法,接收get方式請求
        session = session_lei.Session(self,1)    #創建session對象,cookie保留1天
        if session['zhuangtai'] == True:         #判斷session里的zhuangtai等於True
            self.render("index.html")            #顯示查看頁面
        else:
            self.redirect("/dlu")                #跳轉到登錄頁面

class dluHandler(tornado.web.RequestHandler):
    def get(self):
        session = session_lei.Session(self,1)    #創建session對象,cookie保留1天
        if session['zhuangtai'] == True:         #判斷session里的zhuangtai等於True
            self.redirect("/index")              #跳轉到查看頁面
        else:
            self.render("dlu.html",tishi = '請登錄')  #打開登錄頁面
    def post(self):
        yhm = self.get_argument('yhm')               #接收用戶提交的用戶名
        mim = self.get_argument('mim')               #接收用戶提交的密碼
        if yhm == 'admin' and mim == 'admin':        #判斷用戶名和密碼
            session = session_lei.Session(self,1)    #創建session對象,cookie保留1天
            session['yhm'] = yhm                     #將用戶名保存到session
            session['mim'] = mim                     #將密碼保存到session
            session['zhuangtai'] = True              #在session寫入登錄狀態
            self.redirect("/index")                  #跳轉查看頁面
        else:
            self.render("dlu.html",tishi = '用戶名或密碼錯誤') #打開登錄頁面

settings = {                                        #html文件歸類配置,設置一個字典
    "template_path":"views",                     #鍵為template_path固定的,值為要存放HTML的文件夾名稱
    "static_path":"statics",                         #鍵為static_path固定的,值為要存放js和css的文件夾名稱
}

#路由映射
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()

登錄頁面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>請登錄</h1>
    <form method="post" action="/dlu">
        用戶名<input type="text" name="yhm"/>
        密碼<input type="text" name="mim"/>
        <input type="submit" value="提交"/><p style="color: #ff201e">{{tishi}}</p>
    </form>
</body>
</html>

登錄后查看頁面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>測試網站</title>
    <link rel="stylesheet" href='{{static_url("muban.css")}}'>     <!--接收被繼承頁面的css連接-->
</head>
<body>
登錄后才能查看的信息
</body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM