python - 使用 Flask-Login 获取 'str' 对象在 Flask 中没有属性 'is_authenticated'

标签 python flask flask-login

我正在尝试使用 Flask-Login 为 Flask 设置登录。我有一个供用户使用的 CouchDB;客户文档有一个名为“用户”的对象。

class User(UserMixin):
    def __init__ (self, user) :
        self.name = user['name']
        self.password = user['password']
        self.id= user['id']

    def is_active(self):
        return True

    def is_authenticated(self):
        return True

    def is_anonymous(self):
        return False

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


def check_user(id):
    for row in db.query(map_auth):
        if row.value['id'] == id:
            authUser = User(row.value)
            return authUser
        else:
            return "User not found in database"

@login_manager.user_loader
def load_user(id):
    return check_user(id)


@app.route('/login/', methods=['GET','POST'])
def login():  
    if request.method == 'POST':
        for row in db.query(map_auth):
            if row.value['name'] == request.form['name'] and row.value['password'] == request.form['password']:
                authUser = User(row.value)
        flask_login.login_user(authUser)
        app.logger.debug(authUser.name)
        app.logger.debug(authUser.is_authenticated())
        app.logger.debug(authUser.is_active())
        return redirect(url_for('protected'))
    return render_template('login.html')

map_auth 是来自 python-couchdb 的 View 函数。该 View 为用户返回包含以下信息的 JSON 列表:{"name": "xxxx", "id":1, "password": "password"}

我通过在 Python shell 中模拟它来验证 User 类独立工作。当我在 Flask 中使用它时,出现以下错误。

  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 2000, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1991, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1567, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1639, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1625, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/usr/local/lib/python2.7/dist-packages/flask_login.py", line 790, in decorated_view
    elif not current_user.is_authenticated:
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 343, in __getattr__
    return getattr(self._get_current_object(), name)
AttributeError: 'str' object has no attribute 'is_authenticated'

我已经验证了我使用的 authUser 对象的 is_authenticated() 为真。

最佳答案

如果用户 ID 无效,user_loader 函数(在您的情况下,逻辑在 check_user 中)应该返回 None。在您的情况下,返回一个字符串 "User not found in database",这会创建您遇到的异常。

如果用户 ID 无效,则返回 None

Documenation :

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

关于python - 使用 Flask-Login 获取 'str' 对象在 Flask 中没有属性 'is_authenticated',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38343717/

相关文章:

Python递归函数超出了递归限制。如何将其转换为迭代

python - 在 Flask 中,为什么所有 View 都显示在一个文件中?

python - Flask `Base query` 对象不可调用?

python - Django ModelForm 中的 self.instance

python - Matlab 到 Python 稀疏矩阵转换,克服零索引问题

python - 返回 [1,0] 或 [0,1] 的优雅方式

python - 如何在 Flask 中处理 JSON?

javascript - 如何将 NPM 模块与 Flask 一起使用?

flask - 在Kubernetes中安装Apache Airflow 1.10.0-Flask错误

python - login_required 编码下一个参数,重定向失败