一文詳解 Flask-Login
1.介紹
Flask-Login 為 Flask 提供用戶會(huì)話管理。它處理登錄、注銷和長(zhǎng)時(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
:要簡(jiǎn)便地實(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
所指定的視圖。
2.實(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ì)象
為了簡(jiǎn)單起見,我們將使用字典來表示用戶數(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ì)話并將用戶注銷。文章來源:http://www.zghlxwxcb.cn/news/detail-411567.html
@app.route('/logout')
def logout():
flask_login.logout_user()
return 'Logged out'
我們現(xiàn)在有了一個(gè)基本的工作程序,它使用了基于會(huì)話的認(rèn)證。為了使事情圓滿結(jié)束,我們應(yīng)該為登錄失敗提供一個(gè)回調(diào)。文章來源地址http://www.zghlxwxcb.cn/news/detail-411567.html
@login_manager.unauthorized_handler
def unauthorized_handler():
return 'Unauthorized', 401
到了這里,關(guān)于【Python開發(fā)】一文詳解Flask-Login的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!