tornado中cookie和session

使用的web框架:tornado

首先我們要了解爲什麼要用:cookie
百度百科是這樣說的:

Cookie,有時也用其複數形式 Cookies。類型爲“小型文本文件”,是某些網站爲了辨別用戶身份,進行Session跟蹤而儲存在用戶本地終端上的數據(通常經過加密),由用戶客戶端計算機暫時或永久保存的信息 [1] 。

最關鍵的就是進行辨別用戶 ,因爲http是無狀態的,對於瀏覽器來說,每次HTTP請求都是一個新的請求。
1、無加密的cookie

只使用cookie進行用戶的識別,也就是用過瀏覽器的cookie中保存一個值,請求的時候攜帶cookie,我們就可以從cookie中取出這個值,就可以判斷誰是誰了。
tornado中設置
路由

(r"/login", Account.LoginHandle),

視圖處理邏輯

class LoginHandle(tornado.web.RequestHandler):

    def get(self):
        username = self.get_cookie('user')
        if username:
            self.write('{}登錄成功'.format(username))

        else:
            #進入else,說明沒有進行登錄,渲染登錄頁面到瀏覽器中
            self.render('account/login.html')

    def post(self):

        username = self.get_argument('username','')
        password = self.get_argument('password','')

        if username == 'root' and password == '123456':

            self.set_cookie('user',username)
            print(username)
            print(password)
            self.write({'errno':0,'errmsg':'登錄成功'})

        else:
            #如果用戶名和密碼不對就重新重定向到登錄路由中
            self.redirect('/login')

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="" method="post">
{#    {% module xsrf_form_html() %}#}

    username:<input id="username" type="text" name="username" /><br>

	password:<input id="password" type="password" name="password" /> <br>

	<input type="submit" value="登錄" class="login-btn">

</form>
<script src="{{ static_url('js/admin/jquery.min.js') }}"></script>
{#<script src="{{ static_url('js/account/cookie.js') }}"></script>#}
{#<script src="{{ static_url('js/account/login.js') }}"></script>#}


</body>
</html>

當未登錄時,返回login.html頁面。
在這裏插入圖片描述
此時0個cookie。
在這裏插入圖片描述
輸入賬號密碼進行登錄:會進入當前路由的post請求中
在這裏插入圖片描述
登錄成功返回數據:
在這裏插入圖片描述
可以通過瀏覽器查看到設置的cookie

在這裏插入圖片描述
當這時,在進行登錄會看到返回root登錄成功。
在這裏插入圖片描述

2、加密的cookie

就是對cookie的加密,使客戶端看到是是一串加密後的cookie,雖然是加了密的但是還是把信息保存在了客戶端。
因爲是加密的所以我們要設置一個密鑰;密鑰可以自己隨意設置。
也就是'cookie_secret':'yoursecret',這個字段

settings = {
    'debug':True,
    'template_path': os.path.join(os.path.dirname(
            os.path.dirname(__file__)), "templates"),
    'static_path':os.path.join(os.path.dirname(
            os.path.dirname(__file__)), "statics"),
    'static_url_prefix': '/statics/',
    'ui_methods':t_ui_methods,
    'cookie_secret':'yoursecret',
    #'login_url':'/admin/login',
    # 'xsrf_cookies':True,

}

視圖處理邏輯,只是把get_cookie改爲了get_secure_cookie,其它邏輯代碼還是一樣得 另外, html和路由也還是一樣的

class LoginHandle(tornado.web.RequestHandler):

    def get(self):
        # username = self.get_cookie('user')
        username = self.get_secure_cookie('user')
        if username:
            self.write('{}登錄成功'.format(username))

        else:
            #進入else,說明沒有進行登錄,渲染登錄頁面到瀏覽器中
            self.render('account/login.html')

    def post(self):

        username = self.get_argument('username','')
        password = self.get_argument('password','')

        if username == 'root' and password == '123456':

            # self.set_cookie('user',username)
            self.set_secure_cookie('user',username)
            print(username)
            print(password)
            self.write({'errno':0,'errmeg':'登錄成功'})

        else:
            #如果用戶名和密碼不對就重新重定向到登錄路由中
            self.redirect('/login')

可以先把剛纔設置的無加密的cookie刪除。
這是當我們請求登錄頁面時,可以就看到和剛纔一樣,我們未進行登錄。
在這裏插入圖片描述
還是輸入賬號和密碼
在這裏插入圖片描述
還是返回和登錄成功的數據。
在這裏插入圖片描述
這是我們查看cookie中數據:看到內容時已經加密了。
在這裏插入圖片描述
只是在無加密的基礎上加上密鑰進行了加密。

3、session認證

第三種方式進行用戶識別,這次我們不講cookie的值保存在客戶端了,我們把信息保存在服務端,這就用到了session,在客戶端中我們只保留了一個session_id值,然後通過sessio_id再從後端取值,因此我們要用session保存的話,後端需要數據庫進行保存信息。這裏我們使用redis保存。注意:我們保存的是一個字典。

因爲用到第三方包幫助我們進行session認證,
所以要安裝

pip install pycket
pip install redis

設置:可以看到我們加上了pycket這個配置字段,用來連接redis。

settings = {
    'debug':True,
    'template_path': os.path.join(os.path.dirname(
            os.path.dirname(__file__)), "templates"),
    'static_path':os.path.join(os.path.dirname(
            os.path.dirname(__file__)), "statics"),
    'static_url_prefix': '/statics/',
    'ui_methods':t_ui_methods,
    'cookie_secret':'yoursecret',
    'pycket': {
         'engine': 'redis',
         'storage': {
             'host': '127.0.0.1',
             'port': 6379,
             'db_sessions': 10,
             'max_connections': 2 ** 31,
         },
         'cookies': {
             # 設置過期時間
             'expires_days': 2,
             #'expires':None, #秒
         },
     },
    # 'login_url':'/admin/login',
    # 'xsrf_cookies':True,

}

視圖邏輯代碼

from pycket.session import SessionMixin

#繼承SessionMixin這個類,才能使用session
class LoginHandle(SessionMixin,tornado.web.RequestHandler):

    def get(self):
        # username = self.get_cookie('user')
        # username = self.get_secure_cookie('user')
        username = self.session.get('user')
        if username:
            self.write('{}登錄成功'.format(username))

        else:
            #進入else,說明沒有進行登錄,渲染登錄頁面到瀏覽器中
            self.render('account/login.html')

    def post(self):

        username = self.get_argument('username','')
        password = self.get_argument('password','')

        if username == 'root' and password == '123456':

            # self.set_cookie('user',username)
            # self.set_secure_cookie('user',username)
            self.session.set('user',username)
            print(username)
            print(password)
            self.write({'errno':0,'errmeg':'登錄成功'})

        else:
            #如果用戶名和密碼不對就重新重定向到登錄路由中
            self.redirect('/login')

還是和剛纔一樣請求登錄頁面未進行登錄。
在這裏插入圖片描述
輸入賬號密碼:
在這裏插入圖片描述
登陸成功:
在這裏插入圖片描述
看到給我們的不是user了,而是一個id
在這裏插入圖片描述
當我們第一次請求的時候,就已經給我們設置了一個session_id
在這裏插入圖片描述
每次請求cookie中攜帶session_id值:
在這裏插入圖片描述
這時我們的redis數據庫中就已經保存了這個值(字典):

進入數據庫,因爲我們選擇的是10號數據庫:
在這裏插入圖片描述
我們看到redis中有個進行了字典對象序列化的值;

我們進行反序列化:

import pickle

data = b'\x80\x03}q\x00X\x04\x00\x00\x00userq\x01X\x04\x00\x00\x00rootq\x02s.'

a = pickle.loads(data)

print(a)

我們就可以看到在數據庫中保存的就是設置的session數據.
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章