Python Flask-Login實(shí)現(xiàn)用戶會(huì)話管理
Flask-Login 為 Flask 提供用戶會(huì)話管理。它處理登錄、注銷和長時(shí)間記住用戶會(huì)話等常見任務(wù)。
Flask-Login 不綁定到任何特定的數(shù)據(jù)庫系統(tǒng)或權(quán)限模型。唯一的要求是您的 用戶對(duì)象實(shí)現(xiàn)一些方法,并且您向能夠 從用戶 ID 加載用戶 的擴(kuò)展提供回調(diào)。
GitHub:https://github.com/maxcountryman/flask-login
LoginManager
是一個(gè)類,有多個(gè)方法和屬性;該類初始化的對(duì)象用于保存用于登錄的設(shè)置。LoginManager 實(shí)例不綁定到特定應(yīng)用程序,因此可以在代碼的主體中創(chuàng)建一個(gè),然后將其綁定到您的應(yīng)用程序 app 中工廠函數(shù)。
login-view
:驗(yàn)證失敗跳轉(zhuǎn)的界面。login-message
:用戶重定向到登錄頁面時(shí)閃出的消息。refresh-view
:用戶需要重新進(jìn)行身份驗(yàn)證時(shí)要重定向到的視圖的名稱。needs-refresh-message
:用戶重定向到 “需要刷新” 頁面時(shí)閃出的消息。session-protection
:使用會(huì)話保護(hù)的模式。這可以是basic
(默認(rèn))或strong
,或None
禁用。
class LoginManager: def __init__(self, app=None, add_context_processor=True): #: A class or factory function that produces an anonymous user, which #: is used when no one is logged in. self.anonymous_user = AnonymousUserMixin #: The name of the view to redirect to when the user needs to log in. #: (This can be an absolute URL as well, if your authentication #: machinery is external to your application.) self.login_view = None #: Names of views to redirect to when the user needs to log in, #: per blueprint. If the key value is set to None the value of #: :attr:`login_view` will be used instead. self.blueprint_login_views = {} #: The message to flash when a user is redirected to the login page. self.login_message = LOGIN_MESSAGE #: The message category to flash when a user is redirected to the login #: page. self.login_message_category = LOGIN_MESSAGE_CATEGORY #: The name of the view to redirect to when the user needs to #: reauthenticate. self.refresh_view = None #: The message to flash when a user is redirected to the 'needs #: refresh' page. self.needs_refresh_message = REFRESH_MESSAGE #: The message category to flash when a user is redirected to the #: 'needs refresh' page. self.needs_refresh_message_category = REFRESH_MESSAGE_CATEGORY #: The mode to use session protection in. This can be either #: ``'basic'`` (the default) or ``'strong'``, or ``None`` to disable #: it. self.session_protection = "basic" ......
user_loader
:自定義回調(diào)函數(shù)。這將設(shè)置從會(huì)話重新加載用戶的回調(diào)。您設(shè)置的函數(shù)應(yīng)該使用 用戶 ID(“unicode”)并返回用戶對(duì)象,如果用戶不存在則返回 “None”。源碼如下:
def user_loader(self, callback): """ This sets the callback for reloading a user from the session. The function you set should take a user ID (a ``str``) and return a user object, or ``None`` if the user does not exist. :param callback: The callback for retrieving a user object. :type callback: callable """ self._user_callback = callback return self.
自定義回調(diào)函數(shù)。在執(zhí)行下面這段代碼之后,注冊(cè)了 load_user()
這個(gè)自定義的 callback
。
@login_manager.user_loader def load_user(userid): return User.get(userid)
utils
login_required
:如果使用此裝飾視圖,它將確保在調(diào)用實(shí)際視圖之前登錄并驗(yàn)證當(dāng)前用戶。如果驗(yàn)證不通過,那么則會(huì)調(diào)用LoginManager.unauthorized()
。login_user
:記錄 / 保存當(dāng)前成功登陸的用戶。logout_user
:登出功能類似,除了基本的操作外,還需要把 flask-login 中的登出進(jìn)行操作。
UserMixin
:要簡便地實(shí)現(xiàn)用戶類,你可以從 UserMixin
繼承,它提供了對(duì)下列這些方法的默認(rèn)實(shí)現(xiàn)。(雖然這不是必須的。)
is_authenticated
:當(dāng)用戶通過驗(yàn)證時(shí),也即提供有效證明時(shí)返回True
。(只有通過驗(yàn)證的用戶會(huì)滿足login_required
的條件。)is_active
:如果這是一個(gè)活動(dòng)用戶且通過驗(yàn)證,賬戶也已激活,未被停用,也不符合任何你的應(yīng)用拒絕一個(gè)賬號(hào)的條件,返回True
。不活動(dòng)的賬號(hào)可能不會(huì)登入(當(dāng)然, 是在沒被強(qiáng)制的情況下)。is_anonymous
:如果是一個(gè)匿名用戶,返回True
。(真實(shí)用戶應(yīng)返回False
。)get_id()
:返回一個(gè)能唯一識(shí)別用戶的,并能用于從user_loader
回調(diào)中加載用戶的unicode
。注意必須是一個(gè)unicode
,如果 ID 原本是一個(gè)int
或其它類型,你需要把它轉(zhuǎn)換為unicode
。
Flask-Login 一般使用基礎(chǔ)流程
Flask-Login 通過 user session,提供登錄的常見任務(wù),比如登入 (logging in)、登出 (logging out) 和當(dāng)前用戶 (current user)。
login_user()
:實(shí)現(xiàn)用戶的登入,一般在登入的視圖函數(shù)中調(diào)用。
logout_user()
:實(shí)現(xiàn)登出功能。
current_user
屬性:獲取當(dāng)前用戶。
如果需要頁面是授權(quán)用戶才可見,在相應(yīng)視圖函數(shù)前加上 @login_required
裝飾器進(jìn)行聲明即可,@login_required
裝飾器對(duì)于未登錄用戶訪問,默認(rèn)處理是重定向到 LoginManager.login_view
所指定的視圖。
實(shí)戰(zhàn)
首先,我們將設(shè)置一個(gè) Flask 應(yīng)用程序:
import flask app = flask.Flask(__name__) app.secret_key = 'super secret string' # Change this!
Flask-Login 通過登錄管理器工作。首先,我們將通過實(shí)例化登錄管理器并告訴它我們的 Flask 應(yīng)用程序來設(shè)置登錄管理器:
import flask_login login_manager = flask_login.LoginManager() # 初始化一個(gè) LoginManager 類對(duì)象 login_manager.login_view = 'login' login_manager.login_message_category = 'info' login_manager.login_message = 'Access denied.' login_manager.init_app(app) # 配置該對(duì)象
為了簡單起見,我們將使用字典來表示用戶數(shù)據(jù)庫。在實(shí)際應(yīng)用程序中,這將是一個(gè)實(shí)際的持久層。然而,重要的是要指出這是 Flask-Login 的一個(gè)特性:它不關(guān)心你的數(shù)據(jù)是如何存儲(chǔ)的,只要你告訴它如何檢索它!
# Our mock database. users = {'foo@bar.tld': {'password': 'secret'}}
我們還需要告訴 Flask-Login 如何從 Flask 請(qǐng)求及其會(huì)話中 加載用戶。為此,我們需要定義我們的用戶對(duì)象、一個(gè) user_loader
回調(diào)和一個(gè) request_loader
回調(diào)。
class User(flask_login.UserMixin): pass @login_manager.user_loader def user_loader(email): if email not in users: return user = User() user.id = email return user @login_manager.request_loader def request_loader(request): email = request.form.get('email') if email not in users: return user = User() user.id = email return user
現(xiàn)在我們準(zhǔn)備定義我們的觀點(diǎn)。我們可以從登錄視圖開始,它將使用身份驗(yàn)證位填充會(huì)話。之后我們可以定義一個(gè)需要身份驗(yàn)證的視圖。
@app.route('/login', methods=['GET', 'POST']) def login(): if flask.request.method == 'GET': return ''' <form action='login' method='POST'> <input type='text' name='email' id='email' placeholder='email'/> <input type='password' name='password' id='password' placeholder='password'/> <input type='submit' name='submit'/> </form> ''' email = flask.request.form['email'] if email in users and flask.request.form['password'] == users[email]['password']: user = User() user.id = email flask_login.login_user(user) return flask.redirect(flask.url_for('protected')) return 'Bad login' @app.route('/protected') @flask_login.login_required def protected(): return 'Logged in as: ' + flask_login.current_user.id
最后,我們可以定義一個(gè)視圖來清除會(huì)話并將用戶注銷。
@app.route('/logout') def logout(): flask_login.logout_user() return 'Logged out'
我們現(xiàn)在有了一個(gè)基本的工作程序,它使用了基于會(huì)話的認(rèn)證。為了使事情圓滿結(jié)束,我們應(yīng)該為登錄失敗提供一個(gè)回調(diào)。
@login_manager.unauthorized_handler def unauthorized_handler(): return 'Unauthorized', 401
到此這篇關(guān)于Python Flask-Login實(shí)現(xiàn)用戶會(huì)話管理的文章就介紹到這了,更多相關(guān)Python Flask-Login內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用Python操作Excel中的各項(xiàng)頁面設(shè)置功能
在使用Excel進(jìn)行數(shù)據(jù)分析或報(bào)告制作時(shí),頁面設(shè)置是確保最終輸出效果專業(yè)、美觀的關(guān)鍵步驟,合理的頁面設(shè)置不僅能夠優(yōu)化打印效果,還能提升數(shù)據(jù)的可讀性,本文將詳細(xì)介紹如何使用Python操作Excel中的各項(xiàng)頁面設(shè)置功能,需要的朋友可以參考下2024-08-08Python3.4實(shí)現(xiàn)從HTTP代理網(wǎng)站批量獲取代理并篩選的方法示例
這篇文章主要介紹了Python3.4實(shí)現(xiàn)從HTTP代理網(wǎng)站批量獲取代理并篩選的方法,涉及Python網(wǎng)絡(luò)連接、讀取、判斷等相關(guān)操作技巧,需要的朋友可以參考下2017-09-09python網(wǎng)絡(luò)編程之TCP通信實(shí)例和socketserver框架使用例子
這篇文章主要介紹了python網(wǎng)絡(luò)編程之TCP通信實(shí)例和socketserver框架使用例子,需要的朋友可以參考下2014-04-04python解析Chrome瀏覽器歷史瀏覽記錄和收藏夾數(shù)據(jù)
大家好,本篇文章主要講的是python解析Chrome瀏覽器歷史瀏覽記錄和收藏夾數(shù)據(jù),感興趣的同學(xué)趕快來看一看吧,對(duì)你有幫助的話記得收藏一下2022-02-02使用django和vue進(jìn)行數(shù)據(jù)交互的方法步驟
這篇文章主要介紹了使用django和vue進(jìn)行數(shù)據(jù)交互的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11Python3.6實(shí)現(xiàn)連接mysql或mariadb的方法分析
這篇文章主要介紹了Python3.6實(shí)現(xiàn)連接mysql或mariadb的方法,結(jié)合實(shí)例形式分析了Python3.6針對(duì)mysql或mariadb數(shù)據(jù)庫操作的相關(guān)模塊安裝、數(shù)據(jù)庫與表的創(chuàng)建、數(shù)據(jù)庫連接等操作技巧與注意事項(xiàng),需要的朋友可以參考下2018-05-05150行Python代碼實(shí)現(xiàn)帶界面的數(shù)獨(dú)游戲
這篇文章主要介紹了150行Python代碼實(shí)現(xiàn)帶界面的數(shù)獨(dú)游戲,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04