Flask-Login  烧瓶登录¶

Flask-Login provides user session management for Flask. It handles the common tasks of logging in, logging out, and remembering your users’ sessions over extended periods of time.
Flask-Login 为 Flask 提供用户会话管理。它处理登录、注销和长时间记住用户会话的常见任务。

It will:  它将:

  • Store the active user’s ID in the session, and let you log them in and out easily.
    将活动用户的 ID 存储在会话中,并让您轻松登录和注销。

  • Let you restrict views to logged-in (or logged-out) users.
    允许您将视图限制为已登录(或已注销)的用户。

  • Handle the normally-tricky “remember me” functionality.
    处理通常很棘手的 “remember me” 功能。

  • Help protect your users’ sessions from being stolen by cookie thieves.
    帮助保护用户的会话不被 Cookie 窃贼窃取。

  • Possibly integrate with Flask-Principal or other authorization extensions later on.
    稍后可能会与 Flask-Principal 或其他授权扩展集成。

However, it does not:
但是,它不会:

  • Impose a particular database or other storage method on you. You are entirely in charge of how the user is loaded.
    将特定的数据库或其他存储方法强加给您。您完全负责如何加载用户。

  • Restrict you to using usernames and passwords, OpenIDs, or any other method of authenticating.
    限制您使用用户名和密码、OpenID 或任何其他身份验证方法。

  • Handle permissions beyond “logged in or not.”
    处理“是否登录”之外的权限。

  • Handle user registration or account recovery.
    处理用户注册或帐户恢复。

Installation  安装¶

Install the extension with pip:
使用 pip 安装扩展:

$ pip install flask-login

Configuring your Application
配置您的应用程序¶

The most important part of an application that uses Flask-Login is the LoginManager class. You should create one for your application somewhere in your code, like this:
使用 Flask-Login 的应用程序中最重要的部分是 LoginManager 类。您应该在代码中的某个位置为您的应用程序创建一个,如下所示:

from flask_login import LoginManager
login_manager = LoginManager()

The login manager contains the code that lets your application and Flask-Login work together, such as how to load a user from an ID, where to send users when they need to log in, and the like.
登录管理器包含允许您的应用程序和 Flask-Login 协同工作的代码,例如如何从 ID 加载用户、当用户需要登录时将用户发送到何处等。

Once the actual application object has been created, you can configure it for login with:
创建实际应用程序对象后,您可以使用以下命令将其配置为登录:

login_manager.init_app(app)

By default, Flask-Login uses sessions for authentication. This means you must set the secret key on your application, otherwise Flask will give you an error message telling you to do so. See the Flask documentation on sessions to see how to set a secret key.
默认情况下,Flask-Login 使用会话进行身份验证。这意味着您必须在应用程序上设置密钥,否则 Flask 会给您一条错误消息,告诉您这样做。请参阅有关会话的 Flask 文档 以了解如何设置密钥。

Warning: Make SURE to use the given command in the “How to generate good secret keys” section to generate your own secret key. DO NOT use the example one.
警告: 确保使用“如何生成良好的密钥”部分中的给定命令来生成您自己的密钥。不要使用示例。

For a complete understanding of available configuration keys, please refer to the source code.
要全面了解可用的配置密钥,请参阅源代码

How it Works  工作原理¶

You will need to provide a user_loader callback. This callback is used to reload the user object from the user ID stored in the session. It should take the str ID of a user, and return the corresponding user object. For example:
您需要提供 user_loader 回调。此回调用于从会话中存储的用户 ID 重新加载用户对象。它应该采用用户的 str ID,并返回相应的用户对象。例如:

@login_manager.user_loader
def load_user(user_id):
    return User.get(user_id)

It should return None (not raise an exception) if the ID is not valid. (In that case, the ID will manually be removed from the session and processing will continue.)
如果 ID 无效,它应该返回 None 不引发异常 )。(在这种情况下,将手动从会话中删除 ID,并继续处理。

Your User Class  您的用户类¶

The class that you use to represent users needs to implement these properties and methods:
用于表示用户的类需要实现以下属性和方法:

is_authenticated

This property should return True if the user is authenticated, i.e. they have provided valid credentials. (Only authenticated users will fulfill the criteria of login_required.)
如果用户已通过身份验证,即他们提供了有效的凭据,则此属性应返回 True。(只有经过身份验证的用户才能满足 login_required 的条件。

is_active

This property should return True if this is an active user - in addition to being authenticated, they also have activated their account, not been suspended, or any condition your application has for rejecting an account. Inactive accounts may not log in (without being forced of course).
如果这是一个活动用户,则此属性应返回 True - 除了经过身份验证之外,他们还激活了他们的帐户,没有被暂停,或者您的应用程序拒绝帐户的任何条件。非活动帐户可能无法登录(当然不会被强制)。

is_anonymous

This property should return True if this is an anonymous user. (Actual users should return False instead.)
如果这是匿名用户,则此属性应返回 True。(实际用户应返回 False

get_id()

This method must return a str that uniquely identifies this user, and can be used to load the user from the user_loader callback. Note that this must be a str - if the ID is natively an int or some other type, you will need to convert it to str.
此方法必须返回一个唯一标识此用户的 str,并可用于从 user_loader 加载用户 回调。请注意,这必须str - 如果 ID 本身是 int 或其他类型,则需要将其转换为 str

To make implementing a user class easier, you can inherit from UserMixin, which provides default implementations for all of these properties and methods. (It’s not required, though.)
为了使实现用户类更容易,您可以继承自 UserMixin,它为所有这些属性和方法提供了默认实现。(不过,这不是必需的。

Login Example  登录示例¶

Once a user has authenticated, you log them in with the login_user function.
用户通过身份验证后,您可以使用 login_user 功能。

For example:  例如:

@app.route('/login', methods=['GET', 'POST'])
def login():
    # Here we use a class of some kind to represent and validate our
    # client-side form data. For example, WTForms is a library that will
    # handle this for us, and we use a custom LoginForm to validate.
    form = LoginForm()
    if form.validate_on_submit():
        # Login and validate the user.
        # user should be an instance of your `User` class
        login_user(user)

        flask.flash('Logged in successfully.')

        next = flask.request.args.get('next')
        # is_safe_url should check if the url is safe for redirects.
        # See http://flask.pocoo.org/snippets/62/ for an example.
        if not is_safe_url(next):
            return flask.abort(400)

        return flask.redirect(next or flask.url_for('index'))
    return flask.render_template('login.html', form=form)

Warning: You MUST validate the value of the next parameter. If you do not, your application will be vulnerable to open redirects. For an example implementation of is_safe_url see this Flask Snippet.
警告: 您必须验证下一个参数的值。否则,您的应用程序将容易受到打开重定向的攻击。有关 is_safe_url 的示例实现,请参阅此 Flask Snippet

It’s that simple. You can then access the logged-in user with the current_user proxy, which is available in every template:
就这么简单。然后,您可以使用 current_user 代理,在每个模板中都可用:

{% if current_user.is_authenticated %}
  Hi {{ current_user.name }}!
{% endif %}

Views that require your users to be logged in can be decorated with the login_required decorator:
需要用户登录的视图可以使用 login_required 装饰器进行装饰:

@app.route("/settings")
@login_required
def settings():
    pass

When the user is ready to log out:
当用户准备好注销时:

@app.route("/logout")
@login_required
def logout():
    logout_user()
    return redirect(somewhere)

They will be logged out, and any cookies for their session will be cleaned up.
他们将被注销,并且其会话的所有 Cookie 都将被清理。

Customizing the Login Process
自定义登录过程¶

By default, when a user attempts to access a login_required view without being logged in, Flask-Login will flash a message and redirect them to the log in view. (If the login view is not set, it will abort with a 401 error.)
默认情况下,当用户尝试在不登录的情况下访问 login_required 视图时,Flask-Login 将闪烁一条消息并将其重定向到登录视图。(如果未设置登录视图,它将中止并显示 401 错误。

The name of the log in view can be set as LoginManager.login_view. For example:
log in view 的名称可以设置为 LoginManager.login_view。例如:

login_manager.login_view = "users.login"

The default message flashed is Please log in to access this page. To customize the message, set LoginManager.login_message:
闪烁的默认消息是 Please log in to access this page. To customize the message, set LoginManager.login_message

login_manager.login_message = u"Bonvolu ensaluti por uzi tiun paĝon."

To customize the message category, set LoginManager.login_message_category:
要自定义消息类别,请设置 LoginManager.login_message_category

login_manager.login_message_category = "info"

When the log in view is redirected to, it will have a next variable in the query string, which is the page that the user was trying to access. Alternatively, if USE_SESSION_FOR_NEXT is True, the page is stored in the session under the key next.
当登录视图被重定向到时,它将在查询字符串中具有下一个变量,即用户尝试访问的页面。或者,如果 USE_SESSION_FOR_NEXTTrue,则页面将存储在会话中的键 next 下。

If you would like to customize the process further, decorate a function with LoginManager.unauthorized_handler:
如果您想进一步自定义流程,请使用 LoginManager.unauthorized_handler

@login_manager.unauthorized_handler
def unauthorized():
    # do stuff
    return a_response

For example: You are using Flask Login with Flask Restful. In your API (blueprint named as api) you don’t wanna redirect to login page but return Unauthorized status code .:
例如:您正在将 Flask Login 与 Flask Restful 一起使用。在您的 API(名为 api 的蓝图)中,您不想重定向到登录页面,但返回 Unauthorized 状态代码 .:

from flask import redirect, url_for, request
from http import HTTPStatus
@login_manager.unauthorized_handler
def unauthorized():
    if request.blueprint == 'api':
        abort(HTTPStatus.UNAUTHORIZED)
    return redirect(url_for('site.login'))

Login using Authorization header
使用 Authorization 标头登录¶

Caution  谨慎

This method will be deprecated; use the request_loader below instead.
此方法将被弃用;使用 request_loader

Sometimes you want to support Basic Auth login using the Authorization header, such as for api requests. To support login via header you will need to provide a header_loader callback. This callback should behave the same as your user_loader callback, except that it accepts a header value instead of a user id. For example:
有时您希望使用 Authorization 支持 Basic Auth 登录 标头,例如 API 请求。要支持通过标头登录,您需要 以提供 header_loader 回调。此回调的行为应与您的 user_loader 回调相同,只是它接受 header 值而不是用户 ID。例如:

@login_manager.header_loader
def load_user_from_header(header_val):
    header_val = header_val.replace('Basic ', '', 1)
    try:
        header_val = base64.b64decode(header_val)
    except TypeError:
        pass
    return User.query.filter_by(api_key=header_val).first()

By default the Authorization header’s value is passed to your header_loader callback. You can change the header used with the AUTH_HEADER_NAME configuration.
默认情况下,Authorization 标头的值会传递给 header_loader 回调。您可以更改用于 AUTH_HEADER_NAME 配置的标头。

Custom Login using Request Loader
使用 Request Loader 自定义登录¶

Sometimes you want to login users without using cookies, such as using header values or an api key passed as a query argument. In these cases, you should use the request_loader callback. This callback should behave the same as your user_loader callback, except that it accepts the Flask request instead of a user_id.
有时,您希望在不使用 Cookie 的情况下登录用户,例如使用标头值或作为查询参数传递的 api 密钥。在这些情况下,您应该使用 request_loader 回调。此回调的行为应与 user_loader 回调相同,不同之处在于它接受 Flask 请求而不是 user_id。

For example, to support login from both a url argument and from Basic Auth using the Authorization header:
例如,要支持使用 Authorization 标头从 url 参数和 Basic Auth 登录:

@login_manager.request_loader
def load_user_from_request(request):

    # first, try to login using the api_key url arg
    api_key = request.args.get('api_key')
    if api_key:
        user = User.query.filter_by(api_key=api_key).first()
        if user:
            return user

    # next, try to login using Basic Auth
    api_key = request.headers.get('Authorization')
    if api_key:
        api_key = api_key.replace('Basic ', '', 1)
        try:
            api_key = base64.b64decode(api_key)
        except TypeError:
            pass
        user = User.query.filter_by(api_key=api_key).first()
        if user:
            return user

    # finally, return None if both methods did not login the user
    return None

Anonymous Users  匿名用户¶

By default, when a user is not actually logged in, current_user is set to an AnonymousUserMixin object. It has the following properties and methods:
默认情况下,当用户实际未登录时,current_user 设置为 AnonymousUserMixin 对象。它具有以下属性和方法:

If you have custom requirements for anonymous users (for example, they need to have a permissions field), you can provide a callable (either a class or factory function) that creates anonymous users to the LoginManager with:
如果您对匿名用户有自定义要求(例如,他们需要具有权限字段),则可以提供一个可调用对象(类或工厂函数),该可调用对象使用以下内容向 LoginManager 创建匿名用户:

login_manager.anonymous_user = MyAnonymousUser

Remember Me  记住我¶

By default, when the user closes their browser the Flask Session is deleted and the user is logged out. “Remember Me” prevents the user from accidentally being logged out when they close their browser. This does NOT mean remembering or pre-filling the user’s username or password in a login form after the user has logged out.
默认情况下,当用户关闭浏览器时,Flask 会话将被删除,用户将被注销。“记住我”可防止用户在关闭浏览器时意外注销。这并不意味着在用户注销后记住或预先填写用户的用户名或密码。

“Remember Me” functionality can be tricky to implement. However, Flask-Login makes it nearly transparent - just pass remember=True to the login_user call. A cookie will be saved on the user’s computer, and then Flask-Login will automatically restore the user ID from that cookie if it is not in the session. The amount of time before the cookie expires can be set with the REMEMBER_COOKIE_DURATION configuration or it can be passed to login_user. The cookie is tamper-proof, so if the user tampers with it (i.e. inserts someone else’s user ID in place of their own), the cookie will merely be rejected, as if it was not there.
“Remember Me” 功能可能很难实现。然而,Flask-Login 使它几乎透明——只需将 remember=True 传递给 login_user 叫。一个 cookie 将保存在用户的计算机上,然后 Flask-Login 将自动从该 Cookie 中恢复用户 ID(如果该 Cookie 不在 会期。Cookie 过期前的时间可以通过 REMEMBER_COOKIE_DURATION 配置,也可以将其传递给 login_user。该 Cookie 是防篡改的,因此如果用户篡改它(即插入其他人的用户 ID 代替自己的用户 ID),该 Cookie 只会被拒绝,就像它不存在一样。

That level of functionality is handled automatically. However, you can (and should, if your application handles any kind of sensitive data) provide additional infrastructure to increase the security of your remember cookies.
该级别的功能是自动处理的。但是,您可以(如果您的应用程序处理任何类型的敏感数据,则应该)提供额外的基础设施来提高记住 Cookie 的安全性。

Alternative Tokens  替代代币¶

Using the user ID as the value of the remember token means you must change the user’s ID to invalidate their login sessions. One way to improve this is to use an alternative user id instead of the user’s ID. For example:
使用用户 ID 作为 remember 令牌的值意味着您必须更改用户的 ID 才能使其登录会话失效。改善这种情况的一种方法是使用备用用户 ID 而不是用户的 ID。例如:

@login_manager.user_loader
def load_user(user_id):
    return User.query.filter_by(alternative_id=user_id).first()

Then the get_id method of your User class would return the alternative id instead of the user’s primary ID:
然后,您的 User 类的 get_id 方法将返回备用 ID,而不是用户的主 ID:

def get_id(self):
    return str(self.alternative_id)

This way you are free to change the user’s alternative id to a new randomly generated value when the user changes their password, which would ensure their old authentication sessions will cease to be valid. Note that the alternative id must still uniquely identify the user… think of it as a second user ID.
这样,当用户更改其密码时,您可以自由地将用户的备用 ID 更改为随机生成的新值,这将确保其旧的身份验证会话将不再有效。请注意,备用 ID 仍必须唯一标识用户...将其视为第二个用户 ID。

Fresh Logins  全新登录¶

When a user logs in, their session is marked as “fresh,” which indicates that they actually authenticated on that session. When their session is destroyed and they are logged back in with a “remember me” cookie, it is marked as “non-fresh.” login_required does not differentiate between freshness, which is fine for most pages. However, sensitive actions like changing one’s personal information should require a fresh login. (Actions like changing one’s password should always require a password re-entry regardless.)
当用户登录时,他们的会话被标记为 “fresh”,这表示他们实际上在该会话中进行了身份验证。当他们的会话被销毁并使用“记住我”Cookie 重新登录时,它将被标记为“非新鲜”。login_required 不区分新鲜度,而新鲜度对于大多数页面来说都很好。但是,更改个人信息等敏感作需要重新登录。(无论如何,更改密码等作应始终要求重新输入密码。

fresh_login_required, in addition to verifying that the user is logged in, will also ensure that their login is fresh. If not, it will send them to a page where they can re-enter their credentials. You can customize its behavior in the same ways as you can customize login_required, by setting LoginManager.refresh_view, needs_refresh_message, and needs_refresh_message_category:
fresh_login_required 除了验证用户是否已登录外,还将确保其登录是最新的。如果没有,它会将他们发送到一个页面,他们可以在其中重新输入他们的凭证。您可以按照自定义 login_required 的相同方式自定义其行为,方法是将 LoginManager.refresh_viewneeds_refresh_messageneeds_refresh_message_category :

login_manager.refresh_view = "accounts.reauthenticate"
login_manager.needs_refresh_message = (
    u"To protect your account, please reauthenticate to access this page."
)
login_manager.needs_refresh_message_category = "info"

Or by providing your own callback to handle refreshing:
或者通过提供您自己的回调来处理刷新:

@login_manager.needs_refresh_handler
def refresh():
    # do stuff
    return a_response

To mark a session as fresh again, call the confirm_login function.
要再次将会话标记为 fresh,请调用 confirm_login 函数。

Session Protection  会话保护¶

While the features above help secure your “Remember Me” token from cookie thieves, the session cookie is still vulnerable. Flask-Login includes session protection to help prevent your users’ sessions from being stolen.
虽然上述功能有助于保护您的“Remember Me”令牌免受 Cookie 窃贼的侵害,但会话 Cookie 仍然容易受到攻击。Flask-Login 包括会话保护,以帮助防止用户的会话被盗。

You can configure session protection on the LoginManager, and in the app’s configuration. If it is enabled, it can operate in either basic or strong mode. To set it on the LoginManager, set the session_protection attribute to "basic" or "strong":
您可以在 LoginManager 上和应用程序的配置中配置会话保护。如果启用,它可以在 BasicStrong 中运行 模式。要在 LoginManager 上设置它,请将 session_protection 属性设置为 “basic”“strong”

login_manager.session_protection = "strong"

Or, to disable it:
或者,要禁用它:

login_manager.session_protection = None

By default, it is activated in "basic" mode. It can be disabled in the app’s configuration by setting the SESSION_PROTECTION setting to None, "basic", or "strong".
默认情况下,它在 “basic” 模式下激活。可以通过将 SESSION_PROTECTION 设置为 None 在应用程序的配置中禁用它, “basic”“strong”。

When session protection is active, each request, it generates an identifier for the user’s computer (basically, a secure hash of the IP address and user agent). If the session does not have an associated identifier, the one generated will be stored. If it has an identifier, and it matches the one generated, then the request is OK.
当会话保护处于活动状态时,每个请求都会为用户的计算机生成一个标识符(基本上是 IP 地址和用户代理的安全哈希)。如果会话没有关联的标识符,则将存储生成的标识符。如果它有标识符,并且与生成的标识符匹配,则请求正常。

If the identifiers do not match in basic mode, or when the session is permanent, then the session will simply be marked as non-fresh, and anything requiring a fresh login will force the user to re-authenticate. (Of course, you must be already using fresh logins where appropriate for this to have an effect.)
如果标识符在基本模式下不匹配,或者当会话是永久的时,则会话将被简单地标记为非新会话,并且任何需要新登录的内容都将强制用户重新进行身份验证。(当然,您必须在适当的情况下已经使用新的登录信息才能产生效果。

If the identifiers do not match in strong mode for a non-permanent session, then the entire session (as well as the remember token if it exists) is deleted.
如果标识符在非永久会话的模式下不匹配,则整个会话(以及 remember 令牌,如果存在)将被删除。

Automated Testing  自动化测试¶

To make it easier for you to write automated tests, Flask-Login provides a simple, custom test client class that will set the user’s login cookie for you: FlaskLoginClient. To use this custom test client class, assign it to the test_client_class attribute on your application object, like this:
为了让你更容易编写自动化测试,Flask-Login 提供了一个 简单的自定义测试客户端类,该类将为您设置用户的登录 Cookie: FlaskLoginClient 的 LoginClient 中。要使用此自定义测试客户端类,请将其分配给 test_client_class application 对象上的属性,如下所示:

from flask_login import FlaskLoginClient

app.test_client_class = FlaskLoginClient

Next, use the app.test_client() method to make a test client, as you normally do. However, now you can pass a user object to this method, and your client will be automatically logged in with this user!
接下来,像往常一样,使用 app.test_client() 方法创建一个测试客户端。但是,现在你可以将 user 对象传递给此方法,你的客户端将自动使用此用户登录!

def test_request_with_logged_in_user():
    user = User.query.get(1)
    with app.test_client(user=user) as client:
        # This request has user 1 already logged in!
        client.get("/")

You may also pass fresh_login (bool, defaults to True) to mark the current login as fresh or non-fresh.
您还可以传递 fresh_loginbool,默认为 True) 以将当前登录标记为 fresh 或 non-fresh。

Note that you must use keyword arguments, not positional arguments. E.g. test_client(user=user) will work, but test_client(user) will not.
请注意,您必须使用关键字参数,而不是位置参数。例如 test_client(user=user) 将起作用,但 test_client(user) 不会。

Due to the way this custom test client class is implemented, you may have to disable session protection to have your tests work properly. If session protection is enabled, login sessions will be marked non-fresh in basic mode or outright rejected in strong mode when performing requests with the test client.
由于此自定义测试客户端类的实现方式,您可能必须禁用会话保护才能使测试正常工作。如果启用了会话保护,则在使用测试客户端执行请求时,登录会话将在基本模式下标记为 non-fresh,或在模式下被彻底拒绝。

Localization  本地化¶

By default, the LoginManager uses flash to display messages when a user is required to log in. These messages are in English. If you require localization, set the localize_callback attribute of LoginManager to a function to be called with these messages before they’re sent to flash, e.g. gettext. This function will be called with the message and its return value will be sent to flash instead.
默认情况下,LoginManager 在需要用户登录时使用 flash 来显示消息。这些消息是英文的。如果需要本地化,请将 LoginManagerlocalize_callback 属性设置为要在将这些消息发送到 flash 之前调用的函数,例如 gettext。此函数将与消息一起调用,其返回值将发送到 flash

API Documentation  API 文档¶

This documentation is automatically generated from Flask-Login’s source code.
本文档是从 Flask-Login 的源代码自动生成的。

Configuring Login  配置登录¶

class flask_login.LoginManager(app=None, add_context_processor=True)
flask_login 类 LoginManagerapp=Noneadd_context_processor=True
[source]  [来源]

This object is used to hold the settings used for logging in. Instances of LoginManager are not bound to specific apps, so you can create one in the main body of your code and then bind it to your app in a factory function.
此对象用于保存用于登录的设置。LoginManager 的实例绑定到特定应用程序,因此您可以在代码的主体中创建一个实例,然后在工厂函数中将其绑定到您的应用程序。

init_app(app, add_context_processor=True)
init_appappadd_context_processor=True
[source]  [来源]

Configures an application. This registers an after_request call, and attaches this LoginManager to it as app.login_manager.
配置应用程序。这将注册一个 after_request 调用,并将此 LoginManager 作为 app.login_manager 附加到它。

Parameters:  参数
unauthorized()
未授权
[source]  [来源]

This is called when the user is required to log in. If you register a callback with LoginManager.unauthorized_handler(), then it will be called. Otherwise, it will take the following actions:
当用户需要登录时,会调用此选项。如果您向 LoginManager.unauthorized_handler() 注册回调,则将调用它。否则,它将执行以下作:

  • Flash LoginManager.login_message to the user.
    向用户 LoginManager.login_message 闪存。

  • If the app is using blueprints find the login view for the current blueprint using blueprint_login_views. If the app is not using blueprints or the login view for the current blueprint is not specified use the value of login_view.
    如果应用正在使用蓝图,请使用 blueprint_login_views 查找当前蓝图的登录视图。如果应用未使用蓝图或未指定当前蓝图的登录视图,请使用 login_view 值。

  • Redirect the user to the login view. (The page they were attempting to access will be passed in the next query string variable, so you can redirect there if present instead of the homepage. Alternatively, it will be added to the session as next if USE_SESSION_FOR_NEXT is set.)
    将用户重定向到登录视图。(他们尝试访问的页面将在下一个查询字符串变量中传递,因此您可以重定向到那里(如果存在)而不是主页。或者,如果设置了 USE_SESSION_FOR_NEXT,它将作为下一个添加到会话中。

If LoginManager.login_view is not defined, then it will simply raise a HTTP 401 (Unauthorized) error instead.
如果未定义 LoginManager.login_view,则它只会引发 HTTP 401(未经授权)错误。

This should be returned from a view or before/after_request function, otherwise the redirect will have no effect.
这应该从视图或 before/after_request 函数返回,否则重定向将无效。

needs_refresh()
needs_refresh
[source]  [来源]

This is called when the user is logged in, but they need to be reauthenticated because their session is stale. If you register a callback with needs_refresh_handler, then it will be called. Otherwise, it will take the following actions:
当用户登录时,会调用此作,但需要重新进行身份验证,因为他们的会话已过时。如果您向 needs_refresh_handler 注册回调,则将调用它。否则,它将执行以下作:

If LoginManager.refresh_view is not defined, then it will simply raise a HTTP 401 (Unauthorized) error instead.
如果未定义 LoginManager.refresh_view,则它只会引发 HTTP 401(未经授权)错误。

This should be returned from a view or before/after_request function, otherwise the redirect will have no effect.
这应该从视图或 before/after_request 函数返回,否则重定向将无效。

General Configuration  常规配置

user_loader(callback)
user_loader 回调
[source]  [来源]

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.
这将设置用于从会话重新加载用户的回调。您设置的函数应采用用户 ID (str) 并返回用户对象,如果用户不存在,则应返回 None

Parameters:  参数

callback (callable) – The callback for retrieving a user object.
callbackcallable) – 用于检索用户对象的回调。

request_loader(callback)
request_loader 回调
[source]  [来源]

This sets the callback for loading a user from a Flask request. The function you set should take Flask request object and return a user object, or None if the user does not exist.
这将设置从 Flask 请求加载用户的回调。您设置的函数应该接受 Flask 请求对象并返回一个用户对象,或者如果用户不存在,则返回 None

Parameters:  参数

callback (callable) – The callback for retrieving a user object.
callbackcallable) – 用于检索用户对象的回调。

anonymous_user

A class or factory function that produces an anonymous user, which is used when no one is logged in.
生成匿名用户的类或工厂函数,在没有人登录时使用。

unauthorized Configuration
未经 授权配置

login_view

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.)
当用户需要登录时要重定向到的视图的名称。(如果身份验证机制位于应用程序外部,这也可以是绝对 URL。

blueprint_login_views

This is similar to login_view, except it is used when working with blueprints. It is a dictionary that can store multiple views to redirect to for different blueprints. The redirects are listed in the form of key as the blueprint’s name and value as the redirect to route.
这与 login_view 类似,只是在处理蓝图时使用。它是一个字典,可以存储多个视图以重定向到不同的蓝图。重定向以键的形式列出为蓝图的名称,以值的形式列为重定向到路由。

login_message

The message to flash when a user is redirected to the login page.
当用户被重定向到登录页面时闪烁的消息。

unauthorized_handler(callback)
unauthorized_handler 回调
[source]  [来源]

This will set the callback for the unauthorized method, which among other things is used by login_required. It takes no arguments, and should return a response to be sent to the user instead of their normal view.
这将为未经授权的方法设置回调,除其他外,该方法被 login_required 使用。它不接受任何参数,并且应该返回要发送给用户的响应,而不是他们的正常视图。

Parameters:  参数

callback (callable) – The callback for unauthorized users.
callbackcallable) – 未经授权的用户的回调。

needs_refresh Configuration
needs_refresh 配置

refresh_view

The name of the view to redirect to when the user needs to reauthenticate.
当用户需要重新进行身份验证时要重定向到的视图的名称。

needs_refresh_message

The message to flash when a user is redirected to the reauthentication page.
当用户重定向到重新身份验证页面时闪烁的消息。

needs_refresh_handler(callback)
needs_refresh_handler 回调
[source]  [来源]

This will set the callback for the needs_refresh method, which among other things is used by fresh_login_required. It takes no arguments, and should return a response to be sent to the user instead of their normal view.
这将为 needs_refresh 方法设置回调,除其他外,该方法由 fresh_login_required 使用。它不接受任何参数,并且应该返回要发送给用户的响应,而不是他们的正常视图。

Parameters:  参数

callback (callable) – The callback for unauthorized users.
callbackcallable) – 未经授权的用户的回调。

Login Mechanisms  登录机制¶

flask_login.current_user
flask_login。current_user

A proxy for the current user.
当前用户的代理。

flask_login.login_fresh()
flask_login。login_fresh
[source]  [来源]

This returns True if the current login is fresh.
如果当前登录是新的,则返回 True

flask_login.login_remembered()
flask_login。login_remembered
[source]  [来源]

This returns True if the current login is remembered across sessions.
如果跨会话记住当前登录,则返回 True

flask_login.login_user(user, remember=False, duration=None, force=False, fresh=True)
flask_login。login_useruserremember=Falseduration=Noneforce=Falsefresh=True
[source]  [来源]

Logs a user in. You should pass the actual user object to this. If the user’s is_active property is False, they will not be logged in unless force is True.
登录用户。您应该将实际的用户对象传递给 this。如果用户的 is_active 属性为 False,则除非 forceTrue,否则他们不会登录。

This will return True if the log in attempt succeeds, and False if it fails (i.e. because the user is inactive).
如果登录尝试成功,这将返回 True,如果失败(即因为用户处于非活动状态),这将返回 False

Parameters:  参数
  • user (object) – The user object to log in.
    userobject) – 要登录的用户对象。

  • remember (bool) – Whether to remember the user after their session expires. Defaults to False.
    rememberbool) – 是否在会话到期后记住用户。默认为 false

  • duration (datetime.timedelta) – The amount of time before the remember cookie expires. If None the value set in the settings is used. Defaults to None.
    durationdatetime.timedelta) – 记住 cookie 过期之前的时间量。如果 None 使用设置中设置的值。默认为 None

  • force (bool) – If the user is inactive, setting this to True will log them in regardless. Defaults to False.
    forcebool) – 如果用户处于非活动状态,则将其设置为 True 将不管如何记录他们。默认为 false

  • fresh (bool) – setting this to False will log in the user with a session marked as not “fresh”. Defaults to True.
    freshbool) – 将此设置为 False 将使用标记为非“新鲜”的会话登录用户。默认为 true

flask_login.logout_user()
flask_login。logout_user
[source]  [来源]

Logs a user out. (You do not need to pass the actual user.) This will also clean up the remember me cookie if it exists.
将用户注销。(您不需要传递实际用户。如果存在记住我 cookie,这也会清理它。

flask_login.confirm_login()
flask_login。confirm_login
[source]  [来源]

This sets the current session as fresh. Sessions become stale when they are reloaded from a cookie.
这将当前会话设置为新鲜会话。会话在从 cookie 重新加载时变得过时。

Protecting Views  保护视图¶

flask_login.login_required(func)
flask_login。login_required 功能
[source]  [来源]

If you decorate a view with this, it will ensure that the current user is logged in and authenticated before calling the actual view. (If they are not, it calls the LoginManager.unauthorized callback.) For example:
如果你用这个来装饰一个视图,它将确保在调用实际视图之前,当前用户已经登录并进行了认证。(如果不是,它将调用 LoginManager.unauthorized 回调。例如:

@app.route('/post')
@login_required
def post():
    pass

If there are only certain times you need to require that your user is logged in, you can do so with:
如果只有特定时间需要要求用户登录,则可以使用:

if not current_user.is_authenticated:
    return current_app.login_manager.unauthorized()

…which is essentially the code that this function adds to your views.
…这实质上是此函数添加到视图中的代码。

It can be convenient to globally turn off authentication when unit testing. To enable this, if the application configuration variable LOGIN_DISABLED is set to True, this decorator will be ignored.
在单元测试时全局关闭身份验证可能很方便。要启用此功能,如果应用程序配置变量 LOGIN_DISABLED 设置为 True,则此装饰器将被忽略。

Note  注意

Per W3 guidelines for CORS preflight requests, HTTP OPTIONS requests are exempt from login checks.
根据 CORS 预检请求的 W3 准则 ,HTTP OPTIONS 请求可免于登录检查。

Parameters:  参数

func (function) – The view function to decorate.
funcfunction) – 要装饰的视图函数。

flask_login.fresh_login_required(func)
flask_login。fresh_login_requiredfunc
[source]  [来源]

If you decorate a view with this, it will ensure that the current user’s login is fresh - i.e. their session was not restored from a ‘remember me’ cookie. Sensitive operations, like changing a password or e-mail, should be protected with this, to impede the efforts of cookie thieves.
如果你用这个来装饰视图,它将确保当前用户的登录是最新的 - 即他们的会话不是从 'remember me' cookie 恢复的。敏感作(如更改密码或电子邮件)应使用此功能进行保护,以阻止 cookie 窃贼的努力。

If the user is not authenticated, LoginManager.unauthorized() is called as normal. If they are authenticated, but their session is not fresh, it will call LoginManager.needs_refresh() instead. (In that case, you will need to provide a LoginManager.refresh_view.)
如果用户未通过身份验证,则照常调用 LoginManager.unauthorized()。 如果他们通过身份验证,但他们的会话不是最新的,它将改为调用 LoginManager.needs_refresh() 。(在这种情况下,您需要提供 LoginManager.refresh_view

Behaves identically to the login_required() decorator with respect to configuration variables.
在配置变量方面的行为与 login_required() 装饰器相同。

Note  注意

Per W3 guidelines for CORS preflight requests, HTTP OPTIONS requests are exempt from login checks.
根据 CORS 预检请求的 W3 准则 ,HTTP OPTIONS 请求可免于登录检查。

Parameters:  参数

func (function) – The view function to decorate.
funcfunction) – 要装饰的视图函数。

User Object Helpers  用户对象帮助程序¶

class flask_login.UserMixin
flask_login 类 用户混入
[source]  [来源]

This provides default implementations for the methods that Flask-Login expects user objects to have.
这为 Flask-Login 期望用户对象具有的方法提供了默认实现。

class flask_login.AnonymousUserMixin
flask_login 类 匿名用户混
[source]  [来源]

This is the default object for representing an anonymous user.
这是表示匿名用户的默认对象。

Utilities  工具¶

flask_login.login_url(login_view, next_url=None, next_field='next')
flask_login。login_urllogin_viewnext_url=next_field='下一个'
[source]  [来源]

Creates a URL for redirecting to a login page. If only login_view is provided, this will just return the URL for it. If next_url is provided, however, this will append a next=URL parameter to the query string so that the login view can redirect back to that URL. Flask-Login’s default unauthorized handler uses this function when redirecting to your login url. To force the host name used, set FORCE_HOST_FOR_REDIRECTS to a host. This prevents from redirecting to external sites if request headers Host or X-Forwarded-For are present.
创建用于重定向到登录页面的 URL。如果仅提供 login_view,则只会返回它的 URL。但是 如果提供了 next_url,则会将 next=URL 参数附加到查询字符串,以便登录视图可以重定向回该 URL。Flask-Login 的默认未授权处理程序在重定向到你的登录 URL 时使用这个函数。要强制使用主机名,请将 FORCE_HOST_FOR_REDIRECTS 设置为 host。这可以防止在存在请求标头 Host 或 X-Forwarded-For 时重定向到外部站点。

Parameters:  参数
  • login_view (str) – The name of the login view. (Alternately, the actual URL to the login view.)
    login_viewstr) – 登录视图的名称。(或者,登录视图的实际 URL。

  • next_url (str) – The URL to give the login view for redirection.
    next_urlstr) – 为重定向提供登录视图的 URL。

  • next_field (str) – What field to store the next URL in. (It defaults to next.)
    next_fieldstr) – 将下一个 URL 存储在哪个字段中。(默认为 下一个

class flask_login.FlaskLoginClient(*args, **kwargs)
flask_login 类 FlaskLoginClient*args**kwargs
[source]  [来源]

A Flask test client that knows how to log in users using the Flask-Login extension.
知道如何使用 Flask-Login 扩展登录用户的 Flask 测试客户端。

Signals  信号¶

See the Flask documentation on signals for information on how to use these signals in your code.
有关如何在代码中使用这些信号的信息,请参阅有关 signals 的 Flask 文档

flask_login.user_logged_in
flask_login。user_logged_in

Sent when a user is logged in. In addition to the app (which is the sender), it is passed user, which is the user being logged in.
在用户登录时发送。除了应用程序(即发送者)之外,它还传递 user,即正在登录的用户。

flask_login.user_logged_out
flask_login。user_logged_out

Sent when a user is logged out. In addition to the app (which is the sender), it is passed user, which is the user being logged out.
在用户注销时发送。除了应用程序(即发送者)之外,它还传递 user,即被注销的用户。

flask_login.user_login_confirmed
flask_login。user_login_confirmed

Sent when a user’s login is confirmed, marking it as fresh. (It is not called for a normal login.) It receives no additional arguments besides the app.
确认用户登录时发送,将其标记为 fresh。(正常登录时不会调用它。除了 app 之外,它不会接收任何其他参数。

flask_login.user_unauthorized
flask_login。user_unauthorized

Sent when the unauthorized method is called on a LoginManager. It receives no additional arguments besides the app.
LoginManager 上调用未经授权的方法时发送。除了 app 之外,它不会接收任何其他参数。

flask_login.user_needs_refresh
flask_login。user_needs_refresh

Sent when the needs_refresh method is called on a LoginManager. It receives no additional arguments besides the app.
LoginManager 上调用 needs_refresh 方法时发送。除了 app 之外,它不会接收任何其他参数。

flask_login.session_protected
flask_login。session_protected

Sent whenever session protection takes effect, and a session is either marked non-fresh or deleted. It receives no additional arguments besides the app.
每当会话保护生效时发送,并且会话被标记为 non-fresh 或 deleted。除了 app 之外,它不会接收任何其他参数。