Categories
Python Answers

How to set response headers in Python Flask?

Spread the love

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

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

How to set response headers in Python Flask?

To set response headers in Python Flask, we put the headers in the response.headers dict.

For instance, we write

@app.route("/")
def home():
    resp = flask.Response("Foo bar baz")
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp

to create a response with the flask.Response class by calling it with the response body.

Then we add the Access-Control-Allow-Origin response header with

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

And then we return resp as the response.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *