Skip to main content
 首页 » 编程设计

python之添加装饰器后 Flask 抛出 "Could not build url for endpoint ' 索引'”

2024年12月31日31lori

我有一个用 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("/") 来解决这个问题,但我想永久修复这个问题,这样其他东西可能不会在我相对较大的代码库中停止工作。

请您参考如下方法:

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