我想在Flask中进行外部重定向,以便在使用redirect()
函数并重定向页面时,浏览器中的url应该更改。我知道浏览器必须向服务器发送第二个请求。
我已经构建了一个路由,以便在我请求localhost/profile/342/
或localhost/profile/342/wrong-username/
时,我希望服务器在浏览器中更改URL时提供URL localhost/profile/342/right-username/
。这是我到目前为止的代码:
@appHandler.route('/profile/<int:userid>/', defaults = {'username' : None})
@appHandler.route('/profile/<int:userid>/<username>/')
def profile(userid, username):
user = User.query.filter_by(id = userid).first()
if username != user.username:
redirect(url_for('profile', userid = userid, username = user.username), code = 307)
return render_template('profile/profile.html', user = user)
我尝试给code = 301
(虽然我甚至不确定它是否可行)作为redirect()
函数的参数但它没有用(URL保持不变,但是页面已送达。)
有人有任何建议吗?
答案 0 :(得分:1)
您需要返回 redirect()
生成的响应对象:
if username != user.username:
return redirect(url_for('profile', userid=userid, username=user.username),
code=301)
我在这里选了code=301
; Stack Overflow也使用该状态代码进行用户名重定向。您希望浏览器使用&#39; current&#39;直接使用用户名URL,而不是继续使用错误的用户名。