繁体   English   中英

添加装饰器后,烧瓶抛出“无法为端点“索引”构建URL”

[英]Flask throwing “Could not build url for endpoint 'index'” after adding a decorator

我有一个用flask编写的自定义应用程序,并且尝试添加身份验证装饰器( d_auth ),这样就不必检查用户是否在每个路由功能中都已通过身份验证。 装饰器工作正常,但问题是用户url_for("index")失败。这是我的装饰器代码和在其中添加了装饰器的index路由功能:

def d_auth(func):
    wraps(func)
    def decorated(*ags, **kgs):
        #print("DECORATOR_RUNNING")
        login_valid = (flask.session.get('auth_email') != None)
        if not login_valid: 
            return redirect(url_for("login"))
        else:
            #func(*args, **kwargs)
            return func(*ags, *kgs)
            #pass
    return decorated

@app.route("/", methods=["GET", "POST"])
@d_auth
def index():
    creds = gdrive.get_gdrive_credentials(session['auth_user_id'])
    if not creds:
        info = "<h2 id='lblGAuthStatus' class='text-center text-danger'> <span class='glyphicon glyphicon-alert'></span> NOT Authenticated. <a href='/gdrive_auth'>Click here to Authenticate.</a></h2>"
    elif creds.access_token_expired:
        info = "<h2 id='lblGAuthStatus' class='text-center text-danger'> <span class='glyphicon glyphicon-alert'></span> Access Token EXPIRED. <a href='/gdrive_auth'>Click here to Authenticate.</a></h2>"
    else:
        info = "<h2 id='lblGAuthStatus' class='text-center text-success'> <span class='glyphicon glyphicon-ok'></span> Successfully Authenticated.</h2>"

    return render_template('static/index.html', info=info)

装饰器的基本作用是检查用户是否已登录( not login_valid ),如果尚未登录,则将其重定向到登录页面。 这很完美。 问题是,一旦用户登录并且登录页面尝试将他们再次重定向回索引页面,它将引发以下错误:

werkzeug.routing.BuildError: Could not build url for endpoint 'index'. Did you mean 'view' instead?

这是/login路由的代码:

@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == 'GET':
        return render_template("static/login.html")
    elif request.method == 'POST':
        email = request.form['email']
        password = request.form['password']
        conn, cursor = db.opendb()
        cursor.execute("select id, is_admin, first_name, last_name from user where email=? and password=?", (email, password))
        row = cursor.fetchone()
        if row == None:
            return render_template("static/login.html", error="Invalid Credentials")
        else:
            session['auth_user_id'] = str(row['id'])
            session['auth_email'] = email
            session['auth_first_name'] = row['first_name']
            session['auth_last_name'] = row['last_name']
            session['auth_is_admin'] = row['is_admin']
            return redirect(url_for("index"))

在最后一行,正在调用url_for("index") ,这就是错误的出处。 我知道我可以使用url_for("/")来解决该问题,但是我想永久修复此问题,以便其他事情在我相对较大的代码库中不会停止工作。

我刚刚在这里找到问题的答案。 事实证明,我必须使用@wraps(func)来包装装饰器函数,而不是像我那样简单地wraps(func) 不知道为什么它没有引发错误!

暂无
暂无

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

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