4

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.

2 Answers 2

5

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')
Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.