python - Flask 从外部 API 函数重定向

标签 python flask flask-restful

我在 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/

相关文章:

用于排序键值对的 Python 数据结构

javascript - 动态数据更新,无需刷新或重新加载

python - 类型错误 : key <built-in function id> is not a string

python - 从 angularjs 加载 REST 资源时等待时间非常长

javascript - 使用 render_template 重新渲染不起作用

python - Flask/Flask_restful 自定义 404 错误信息

python - 在任何路径上的 Sphinx 输出中包含文件

python - 在 Pandas 中合并具有相同列名但列数不同的两个数据框

python - 在python中导入excel csv文件

python - flask - "ValueError: Detected newline in header value. This is a potential security prob lem"