简体   繁体   English

AttibuteError: '_AppCtxGlobals' object 没有属性 'user'

[英]AttibuteError: '_AppCtxGlobals' object has no attribute 'user'

To set some context I'm creating an API through Flask.为了设置一些上下文,我正在通过 Flask 创建一个 API。 To authenticate users, I'm using flask-HTTPAuth .为了对用户进行身份验证,我使用了 flask-HTTPAuth As a part of accessing login protected resources, I've defined my verify_password callback in auth.py .作为访问登录保护资源的一部分,我在auth.py中定义了我的verify_password回调。 If the user credentials provided evaluate to True, the user is attached to the g object.如果提供的用户凭据评估为 True,则用户将附加到g object。

In app.py , there is the route /api/v1/users/token , that when requested, a token is issued to a user that is logged in. However when I try to access g.user in app.py , I get the error: AttributeError: '_AppCtxGlobals' object has no attribute 'user' .app.py中,有路由/api/v1/users/token ,当请求时,会向登录的用户发出令牌。但是,当我尝试访问g.user中的app.py时,我得到错误: AttributeError: '_AppCtxGlobals' object has no attribute 'user'

Why isn't there any existing 'user' attribute not while accessing the g object in app.py ?为什么在app.py中访问g object 时没有任何现有的“用户”属性?

auth.py授权文件

from flask import g
from flask_http import HTTPBasicAuth

from models import User

basic_auth = HTTPBasicAuth()

@basic_auth.verify_password
def verify_password(username, password):
    try:
        api_user = User.get(User.username == username)
    except User.DoesNotExist:
        return False
    user_verified = api_user.check_password(password)
    if user_verified:
        g.user = api_user
        return True
    return False

app.py应用程序.py

from flask import Flask, g, jsonify

from auth import basic_auth as auth

app = Flask(__name__)

@auth.login_required
@app.route("/api/v1/users/token")
def issue_api_token():
    token = g.user.request_token()
    return jsonify({'token': token})

The order of your decorators is wrong, @app.route should always be first.你的装饰器的顺序是错误的, @app.route应该总是第一个。

@app.route("/api/v1/users/token")
@auth.login_required
def issue_api_token():
    # ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM