通過cookie驗證用戶登錄


# cookie

# cookie
# 當你在瀏覽器登陸時,瀏覽器記錄這個登錄信息(服務器響應時發送請求的數據和登錄信息),再次訪問時 瀏覽器會將訪問請求和緩存的登錄信息都發送到服務器,
# 服務器通過這個信息判斷用戶是否已經登錄

# @authenticated 需要
# application中配置好 login_url='login', 裝飾器驗證不通過則跳轉到登錄界面
# 寫一個BaseHandler並重寫get_current_user方法(該方法默認返回空)
# 該改寫好 logain的登陸界面

import time
from tornado.web import authenticated   # 裝飾器
from data.user_module import User
define('port',default=8000,help='run port',type=int)  # windows通過Ctrl+鼠標左鍵
define('version',default=0.1,help='version',type=str)


class LoginHandler(tornado.web.RequestHandler):

    def get(self):
        nextname=self.get_argument('next','')  # 從/buy跳轉到登陸界面是字符串傳參自動傳入了next=/buy
但是直接從logain登錄nextname = '',可以根據這點在logain.html中寫if判斷,放入兩個不同的action屬性的form表單
self.render('login.html', nextname=nextname, error='' # login.html用到兩個參數 nextname和error ) def post(self, *args, **kwargs): nextname = self.get_argument('next', '') # 獲取的上個跳轉過來的路由
      # 通過獲取登錄的用戶信息去匹配數據庫 user
= self.get_argument('name', '') username = User.by_name(user) password = self.get_argument('password', '')       # 匹配后做出判斷 if username and password == username[0].password: self.set_secure_cookie('ID',username[0].username) self.redirect(nextname) else: self.render('login.html', # 用戶名或密碼錯誤,再次登陸 nextname=nextname, error='用戶名或密碼錯誤' ) class BaseHandler(tornado.web.RequestHandler): # authenticated裝飾器需要改寫get_current_user def get_current_user(self): current_user = self.get_secure_cookie('ID') if current_user: return current_user return None class BuyHandler(BaseHandler): @authenticated # 裝飾器自動驗證cookie,驗證通過直接訪問/buy,沒有則跳轉到登陸界面 def get(self): self.write('歡迎你,尊貴的vip1000') application = tornado.web.Application( handlers=[ (r"/login",LoginHandler), (r"/buy",BuyHandler) ], template_path='templates', # 表明頁面html的路徑 static_path='static', # 表明靜態文件的位置 cookie_secret='miyao', # 設置密鑰 login_url='login', # 裝飾器驗證不通過則跳轉到登錄界面 debug=True # 上傳代碼后服務器自動重啟 ) if __name__ == '__main__': tornado.options.parse_command_line() # 通過sys.arg獲取命令行輸入參數(python xxx.py --port=xxx) print(options.port) print(options.version) http_server = tornado.httpserver.HTTPServer(application) # 非阻塞 application.listen(options.port) tornado.ioloop.IOLoop.instance().start() # 啟動io循環

 login.html

<body>
             <--!用到了兩個變量 error nextname-->
{% if error %}
    用戶名或密碼錯誤
{% end %}

    <form method="post" action="/login?next={{nextname}}">
        <p>用戶名 <input type="text" name="name"></p><br>
        <p>密碼<input type="password" name="password"></p><br>
        <input type="submit">
    </form>
</body>

 


免責聲明!

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



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