Return a Message with HTTP Error Response Code in Flask?

How can a message body be added to a 404 response in flask?

The following attempts will generate a 404 but without the message:

@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"

Thank you in advance for your consideration and response.

Upvotes: 4

Views: 5708

Answers (2)

0xed
0xed

Reputation: 309

Hellow !

I saw that you have already mentioned this issue as resolved. any way...

  • you can add a description parameter in flask.abord()
    so it make sens to: falsk.abord(404, description="Lorem ipsum dolor...")
    @app.errorhandler(404)
    def page_not_found(e):
        return "{}, {}".format(e.message, e.description)

Upvotes: 2

Ajax1234
Ajax1234

Reputation: 71471

You can add the builtin 404 error handler:

@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')

Upvotes: 5

Related Questions