gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:40:53 24 4
gpt4 key购买 nike

我有一个用 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)。想知道为什么它没有抛出错误!

关于python - 添加装饰器后 Flask 抛出 "Could not build url for endpoint ' 索引'”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50666582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com