在Flask中返回带有HTTP错误响应代码的消息?

时间:2017-12-08 14:40:00

标签: python flask

如何将消息正文添加到烧瓶中的404响应中?

以下尝试将生成404但没有消息:

@app.route('/fruit/<fruit_name>', methods=["GET"])
def fruit_route(fruit_name):
    if fruit_name == "tomato":
        return "I don't care what they say, tomato is not a fruit", 404

    return "yummy"

@app.route('/fruit/<fruit_name>', methods=["GET"])
def fruit_route(fruit_name):
    if fruit_name == "tomato":
        flask.abort(404,"I don't care what they say, tomato is not a fruit")

    return "yummy"

提前感谢您的考虑和回应。

2 个答案:

答案 0 :(得分:3)

您可以添加内置404错误处理程序:

@app.errorhandler(404)
def page_not_found(e):
    return "I don't care what they say, tomato is not a fruit"

@app.route('/fruit/<fruit_name>', methods=["GET"])
def fruit_route(fruit_name):
  if fruit_name == "tomato":
     return flask.redirect('/404')

答案 1 :(得分:2)

Hellow!

我看到你已经提到这个问题已经解决了。无论如何......

  • 您可以在flask.abord()中添加description参数 所以它让人感觉: falsk.abord(404,description =“Lorem ipsum dolor ...”)
    @app.errorhandler(404)
    def page_not_found(e):
        return "{}, {}".format(e.message, e.description)