首页 > 解决方案 > 添加装饰器后,烧瓶抛出“无法为端点'index'构建url”

问题描述

我有一个用烧瓶编写的自定义应用程序,我正在尝试添加一个身份验证装饰器 ( 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("/")这个问题,但我想永久修复这个问题,这样其他东西就不会停止在我相对较大的代码库中工作。

标签: pythonpython-3.xflask

解决方案


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


推荐阅读