我用烧瓶写的自定义应用程序,我试图添加身份验证装饰器(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("/")
来解决这个问题,但是我想永久修复它,以便其他东西可能不会停止在我相对较大的代码库中工作。
答案 0 :(得分:0)
我刚刚找到了问题here的答案。事实证明,我已经使用@wraps(func)
包装装饰器功能,而不仅仅是wraps(func)
,就像我完成的那样。不知道为什么它没有抛出错误!