Reputation: 2097
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?
Upvotes: 7
Views: 7417
Reputation: 403
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.
Upvotes: 0
Reputation: 1510
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.
Upvotes: 0
Reputation: 2418
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
Upvotes: 7