我在 Flask 应用程序中有一个辅助方法,多个端点使用该方法来获取资源。为了避免到处都有多个 redirect_url
调用,我希望能够仅从这个辅助方法进行重定向。抛出 RequestRedirect
异常,如图所示 here正确返回 301
响应,但未设置 Content-Location
错误。为了解决这个问题,我添加了一个 after_this_request
Hook 来设置该响应的 url。
这似乎工作正常,但我想知道是否有更优雅的方法来实现它。
匿名辅助方法:
def get_resource(resource_id):
try:
# Some logic
except:
@after_this_request
def add_header(response):
response.headers['Content-Location'] = url
return response
raise RequestRedirect(new_url='/')
最佳答案
如果它位于您的 API 之外,通常您会重定向到 404 页面。这是一个示例:
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
关于python - Flask 从外部 API 函数重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32317566/