使用flask-login和postgresql [英] using flask-login with postgresql

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

问题描述

我正在开发一个需要验证的应用程序。我已经迷上了烧瓶登录,但它看起来不是很优雅。

第一个烧瓶登录需要确保用户存在:

  @ login_manager.user_loader 
def load_user(id):
返回User.query.get(id)

但是您还需要使用'login_user'来创建用户对象

 #$ b $上面的一些代码user = User.query.filter_by(email = form.email.data,password = form.password.data).first()
user.login_status = 1
db.session.commit()
login_user(object.SignedInUser(user.id,user.email,user.login_status == LoginStatus.Active))
#下面的一些代码

在上面的代码中,User是Postgres的一个模型,SignedInUser只是一个对象将被用于flask-login。



有没有人有一个与postgres一起使用flask-login的例子?

解决方案

看来你可能会误会寻找Flask-Login处理的内容。在你通过认证成功后(通过调用 login_user ),它可以跟踪用户会话的所有内容。 user_loader callback只告诉它如何为已经被认证的用户重新加载对象,例如当某人重新连接到记住我会话时。文档不是特别清楚的。

不应该在数据库中为用户的登录状态保留一个标志。另外,如果凭据不正确(user = None),那么包含的代码将引发AttributeError。

以下是Flask-SQLAlchemy应用程序的示例。它使用外部认证源和SQLAlchemy User对象的包装器,但是过程基本相同。
$ b

user_loader回调:

  @ login_manager.user_loader 
def load_user(user_id):
user = User.query.get(user_id)
if user:
return DbUser(user)
else:
return None

用户类(SQLAlchemy对象的包装):

$ $ $ $ $ $ $ $ $ $ $ $ $ 为Flask登录包装用户对象
def __init __(self,user):
self._user = user
$ b $ get get_id(self):
return unicode(self._user.id)
$ b $ def is_active(self):
return self._user.enabled

def is_anonymous(self):
返回False

def is_authenticated(self):
return True

登录处理程序:

  @ app.route('/ login',methods = ['GET','POST'])
def login():
error = None
next = request.args.get ('next')
if request.method =='POST':
username = request.form ['username']
password = request.form ['password']


如果认证(app.config ['AUTH_SERVER'],用户名,密码):
user = User.query.filter_by(username = username).first()
如果用户:
如果login_user(DbUser(用户)):
#做东西
flash(您已经登录)

return redirect(next or url_for ('index',error = error))
error =登录失败
返回render_template('login.html',login = True,next = next,error = error)

请注意,登录失败,如果:

$ ul

  • 外部验证失败

  • 用户查询返回无(用户不存在t)

  • login_user 返回False( user.is_active()== False



  • 注销

      
    @login_required
    def logout():
    logout_user()
    flash('您已经注销')
    return (redirect(url_for('login')))


    I'm working on a flask app that needs authentication. I've hooked up flask-login but it doesn't seem very graceful.

    First flask-login needs to make sure the user exists:

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

    But you also need to use 'login_user' to create the user object

    # Some code above 
      user = User.query.filter_by(email = form.email.data, password = form.password.data).first()
      user.login_status = 1
      db.session.commit()
      login_user(objects.SignedInUser(user.id, user.email, user.login_status == LoginStatus.Active))    
    # Some code below
    

    In the code above 'User' is a model for postgres and SignedInUser is just an object to be used for flask-login.

    Does anyone have an example of flask-login used with postgres?

    解决方案

    It looks like you might be misunderstanding what Flask-Login handles. It's there to keep track of everything about the user's session after you tell it authentication was successful (by calling login_user.) The user_loader callback only tells it how to reload the object for a user that has already been authenticated, such as when someone reconnects to a "remember me" session. The docs are not especially clear on that.

    There should be no need to keep a flag in the database for the user's login status. Also, the code you included will raise an AttributeError if the credentials are incorrect (user = None).

    Here's an example from a Flask-SQLAlchemy application. It uses an external authentication source and a wrapper for the SQLAlchemy User object, but the process is basically the same.

    user_loader callback:

    @login_manager.user_loader
    def load_user(user_id):
        user = User.query.get(user_id)
        if user:
            return DbUser(user)
        else:
            return None
    

    User class (wrapper for SQLAlchemy object):

    # User class
    class DbUser(object):
        """Wraps User object for Flask-Login"""
        def __init__(self, user):
            self._user = user
    
        def get_id(self):
            return unicode(self._user.id)
    
        def is_active(self):
            return self._user.enabled
    
        def is_anonymous(self):
            return False
    
        def is_authenticated(self):
            return True
    

    Login handler:

    @app.route('/login', methods=['GET', 'POST'])
    def login():
        error = None
        next = request.args.get('next')
        if request.method == 'POST':
            username = request.form['username']
            password = request.form['password']
    
    
            if authenticate(app.config['AUTH_SERVER'], username, password):
                user = User.query.filter_by(username=username).first()
                if user:
                    if login_user(DbUser(user)):
                        # do stuff
                        flash("You have logged in")
    
                        return redirect(next or url_for('index', error=error))
            error = "Login failed"
        return render_template('login.html', login=True, next=next, error=error)
    

    Note that login fails if:

    • external auth fails
    • user query returns None (user does not exist)
    • login_user returns False (user.is_active() == False)

    Logout

    @app.route('/logout')
    @login_required
    def logout():
        logout_user()
        flash('You have logged out')
        return(redirect(url_for('login')))
    

    这篇关于使用flask-login和postgresql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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