Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the HTTP status text in a Flask response

Tags:

python

http

flask

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?

like image 537
sba Avatar asked Oct 18 '17 08:10

sba


1 Answers

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
like image 127
Jayson Chacko Avatar answered Oct 26 '22 04:10

Jayson Chacko