7

How can I set the HTTP status text for a response in Flask?

I know I can return a string with a status code

@app.route('/knockknock')
def knockknock():
    return "sleeping, try later", 500

But that sets the body, I'd like to change the HTTP status text from "INTERNAL SERVER ERROR" to "sleeping, try later".

It seems this is not possible in Flask/Werkzeug. It's not mentioned anywhere. But maybe I'm missing something?

0

3 Answers 3

7

The following will work in Flask. Flask can use either a status code or description while returning response. The description can obviously contain the code as well (from the client side it is identical). However note that this doesn't generate the default error description from the Flask side.

from flask import Flask
app = Flask(__name__)

@app.route('/knockknock')
def knockknock():
    return "", "500 sleeping, try later"

Here is the output from the curl command,

curl -i http://127.0.0.1:5000/knockknock

HTTP/1.0 500 sleeping, try later
Content-Type: text/html; charset=utf-8
3
  • 1
    simple and sweet
    – sba
    Oct 18, 2017 at 8:57
  • This doesn't work for me. Flask always reset the status string to original value, like "NOT FOUND, BAD REQUEST, ...
    – eval
    Nov 4, 2020 at 22:50
  • @eval If you're using HTTP/2, status messages aren't supported (only the number is sent). Source Jun 1 at 20:18
0

I'm not an expert on this, but I'm afraid this will only be possible through monkeypatching.

Flask returns werkzeug Response objects, and it seems that the status code reasons are hardcoded in http.py.

Again, some monkeypatching might be enough to change this for your application however.

0
0

Maybe this document will be helpful,you can customorize your own error page.

http://flask.pocoo.org/docs/0.12/patterns/errorpages/

by review the source code, in app.py can find

if status is not None:
        if isinstance(status, string_types):
            rv.status = status
        else:
            rv.status_code = status

so using

@app.route('/test')
def tt():
    return "status error", "500 msg"

works.

Sorry for the misunderstanding.

1
  • I didn't see any mention of HTTP status text in that document.
    – sba
    Oct 18, 2017 at 8:53

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.