【问题标题】:ValueError: View function did not return a response not caught by Exception exception handlerValueError:视图函数未返回异常异常处理程序未捕获的响应
【发布时间】:2015-09-20 15:54:58
【问题描述】:

我在我的 Flask 应用程序中添加了一个异常处理程序方法来捕获在请求处理期间发生的所有意外错误,以便我可以控制将哪个响应返回给客户端。

@app.errorhandler(Exception)
def handle_default(error):
    utils.log('Unexpected error happened: ' + str(error))
    ...

但是,在处理请求(不返回响应)相应异常时似乎存在程序错误

ValueError: View function did not return a response

随后没有像我预期的那样被这个默认处理程序处理。

为什么会这样? 对此有什么办法?

【问题讨论】:

    标签: python web-applications flask


    【解决方案1】:

    所有 Flask 路由都需要一个隐式响应

    from flask import Flask
    app = Flask("the_flask_module")
    
    @app.route("/")
    def home_page():
        return "I'm An Implicit Response!"
    
    app.run(host="0.0.0.0", port=5000)
    

    或明确的回应

    from flask import Flask, make_response
    app = Flask("the_flask_module")
    
    @app.route("/")
    def home_page():
        response = make_response("I'm an explicit Response!")
        response.headers['Content-Type'] = "Malarkey"
        response.headers['Nonsense'] = "Seattle Never Has Traffic"
        return response
    
    app.run(host="0.0.0.0", port=5000)
    

    这包括错误处理程序

    @app.errorhandler(Exception)
    def handle_default(error):
        utils.log('Unexpected error happened: ' + str(error))
        ...
        return "A string or response object."
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-02
      • 1970-01-01
      • 2018-06-14
      • 2011-09-16
      • 2017-11-25
      • 2018-05-30
      • 2011-05-20
      相关资源
      最近更新 更多