且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

flask-login:无法理解其工作原理

更新时间:2022-06-16 23:12:52

Flask登录实际上没有用户后端,它只是处理会话机制来帮助您登录和注销用户.您必须(通过装饰方法)告诉它代表用户的内容,并且还需要弄清楚如何知道用户是否处于活动状态"(因为活动"可能在不同的应用程序中表示不同的含义) ).

Flask-login doesn't actually have a user backend, it just handles the session machinery to help you login and logout users. You have to tell it (by decorating methods), what represents a user and it is also up to you to figure out how to know if a user is "active" or not (since being "active" can mean different things in different applications).

您应该阅读文档,并确保其作用并没有.在这里,我仅专注于与db后端进行连接.

You should read the documentation and be sure what it does and does not do. Here I am only going to concentrate on wiring it up with the db backend.

首先要定义一个用户对象;代表您的用户的属性.然后,该对象可以查询数据库,LDAP或其他任何东西,它是将登录机制与数据库后端连接起来的钩子.

To start off with, define a user object; which represents properties for your users. This object can then query databases, or LDAP, or whatever and it is the hook that connects the login mechanism with your database backend.

我将为此目的使用登录示例脚本.

I will be using the login example script for this purpose.

class User(UserMixin):
    def __init__(self, name, id, active=True):
        self.name = name
        self.id = id
        self.active = active

    def is_active(self):
        # Here you should write whatever the code is
        # that checks the database if your user is active
        return self.active

    def is_anonymous(self):
        return False

    def is_authenticated(self):
        return True

一旦创建了用户对象,就需要编写一个加载用户的方法(基本上是从上面创建User类的实例).使用用户ID调用此方法.

Once you have the user object created, you need to write a method that loads the user (basically, creates an instance of the User class from above). This method is called with the user id.

@login_manager.user_loader
def load_user(id):
     # 1. Fetch against the database a user by `id` 
     # 2. Create a new object of `User` class and return it.
     u = DBUsers.query.get(id)
    return User(u.name,u.id,u.active)

完成这些步骤后,您的登录方法将执行以下操作:

Once you have these steps, your login method does this:

  1. 检查用户名和密码是否匹配(针对您的数据库)-您需要自己编写此代码.

  1. Checks to see if the username and password match (against your database) - you need to write this code yourself.

如果身份验证成功,则应将用户实例传递给login_user()

If authentication was successful you should pass an instance of the user to login_user()