flask-login:无法理解其工作原理 [英] flask-login: can't understand how it works

查看:139
本文介绍了flask-login:无法理解其工作原理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解 Flask-Login 的工作原理.

I'm trying to understand how Flask-Login works.

我在他们的文档中看到他们使用的是预先填充的用户列表.我想玩一个数据库存储的用户列表.

I see in their documentation that they use a pre-populated list of users. I want to play with a database-stored users list.

但是,我不理解该 Flask-Login 模块中的某些内容.

However, I don't understand some things in this Flask-Login module.

@login_manager.user_loader
def load_user(userid):
    #print 'this is executed',userid
    return user(userid, 'asdf')

每次请求都会调用此代码吗?这是用来加载我的用户对象的所有详细信息吗?

This code will be called at every request? This is used to load all the details of my user object?

现在,我有以下代码:

@app.route('/make-login')
def make_login():
    username = 'asdf'
    password = 'asdf'
    user_data = authenticate(username, password)
    user_obj = user(user_data[0], user_data[1])
    login_user(user_obj)
    return render_template('make-login.html')

当我访问/make-login时,我想登录.

When I access /make-login, I want to log in.

我的用户类别:

class user(object):
    def __init__(self, id, username, active=True):
        self.username = username
        self.id = id
        #self.active = active
    def is_authenticated(self):
        return True  

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return 5

此外,我还编写了另外两个用于身份验证/注册的功能

Also, I wrote another two functions for authenticate/register

def authenticate(username, password):

    cursor = db.cursor()
    password = md5.md5(password).hexdigest()
    try:
        query = "SELECT * FROM `users` WHERE `username` = %s AND `password` = %s"
        cursor.execute(query, (username, password))
        results = cursor.fetchall()
        #print results[0][0]
        #print "here i am"
        if not results:
            return False
        else:
            user_data = [results[0][0], results[0][1]]
            return user_data
            #self.authenticated = True
            #self.user_id = results[0][0]
            #session['username']  = results['username']
            #print type(results)
    except db.Error, e:
        return 'There was a mysql error'    

def register(username, password, email, *args):
    cursor = db.cursor()
    password = md5.md5(password).hexdigest()
    try:
        #query = "INSERT INTO `users` (`username`, `password`, `email`) VALUES ('%s', '%s', '%s')" % (username, password, email)
        query = "INSERT INTO `users` (`username`, `password`, `email`) VALUES (%s, %s, %s)"
        cursor.execute(query, (username, password, email))
        db.commit()
        return True
    except db.Error, e:
        print 'An error has been passed. %s' %e
        db.rollback()
        return False

我不知道该如何使 Flask-Login 与MySQL一起使用.另外,我不知道用户是否已登录.如何获取用户ID或用户名?

I don't know how to make this Flask-Login work with MySQL. Also, I don't know if the user are logged-in. How can I get the user ID or the username?

任何人都可以在某些行中向我解释 Flask-Login 的工作原理吗?

Anyone can explain me in some rows how this Flask-Login works?

推荐答案

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()

这篇关于flask-login:无法理解其工作原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆