Redirect 如何在Flask框架中执行外部重定向

Redirect 如何在Flask框架中执行外部重定向,redirect,flask,Redirect,Flask,我想在Flask中执行一个外部重定向,以便在使用redirect()函数并且重定向页面时,浏览器中的url应该更改。我知道浏览器必须向服务器发送第二个请求 我建立了一个路由,因此当我请求localhost/profile/342/或localhost/profile/342/错误用户名/时,我希望服务器在浏览器中更改URL后为URLlocalhost/profile/342/正确用户名/提供服务。以下是我目前掌握的代码: @appHandler.route('/profile/<int:u

我想在Flask中执行一个外部重定向,以便在使用
redirect()
函数并且重定向页面时,浏览器中的url应该更改。我知道浏览器必须向服务器发送第二个请求

我建立了一个路由,因此当我请求
localhost/profile/342/
localhost/profile/342/错误用户名/
时,我希望服务器在浏览器中更改URL后为URL
localhost/profile/342/正确用户名/
提供服务。以下是我目前掌握的代码:

@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)
@appHandler.route('/profile/',默认值={'username':None})
@appHandler.route(“/profile//”)
def配置文件(用户ID、用户名):
user=user.query.filter\u by(id=userid).first()
如果用户名!=user.username:
重定向(url_用于('profile',userid=userid,username=user.username),代码=307)
返回呈现模板('profile/profile.html',user=user)
我尝试将
code=301
作为
redirect()
函数的参数(尽管我甚至不确定它是否有效),但它不起作用(URL保持不变,但页面被提供)

有人有什么建议吗?

您需要返回由
重定向()生成的响应对象。


我在这里选择了
code=301
;堆栈溢出也将该状态代码用于用户名重定向。您希望浏览器直接使用“当前”用户名URL,而不是重复使用错误的用户名。

Define在这里不起作用。您确实使用了正确的方法,在这种情况下,您应该将HTTP代码保留为默认值。@MartijnPieters我已经更新了问题。请您再解释一下您答案的最后一句话好吗?@kevin:浏览器可以根据从服务器收到的响应缓存URL。307响应表示“请改为查看此处,但对于您的下一个请求,如果您再次使用此URL则可以”,因此缓存或浏览器将继续重新请求用户名不匹配的错误URL。301会告诉他们:“对不起,这是错误的URL,你真的想使用我重定向到的另一个URL”,浏览器或缓存将来会直接转到正确的URL,而不会打扰你的服务器。这一点现在已经清楚了。现在我看到重定向的默认响应代码是302。谢谢
if username != user.username:
    return redirect(url_for('profile', userid=userid, username=user.username),
                    code=301)