Menu Close

How to set response headers in Flask and Python?

Sometimes, we want to set response headers in Flask and Python.

In this article, we’ll look at how to set response headers in Flask and Python.

How to set response headers in Flask and Python?

To set response headers in Flask and Python, we set the headers property of the response object.

For instance, we write

@app.route("/")
def home():
    resp = make_response("hello")
    resp.headers["Access-Control-Allow-Origin"] = "*"
    return resp

to call make_response to create response object that returns a string response.

Then we set the Access-Control-Allow-Origin header with

resp.headers["Access-Control-Allow-Origin"] = "*"

Finally, we return the resp object in the home route.

Conclusion

To set response headers in Flask and Python, we set the headers property of the response object.

Posted in Python, Python Answers