When we respond to content from a server to a client, one of the contents that goes in the response is the headers. Headers usually carry information either about the content of the request or about the server that is serving the request. In this article we are going to see how we can manage the headers in Flask for a request.
The first thing we have to know to be able to manage the headers in Flask is what the responses we return to the client are like. The most used may be to see a template as a response using the render_template() method or simply return a text, either plain or XML or JSON.
Although in all cases what is returned is a response object. If we want to create an empty response object we can use the make_response() method.
So we can create the following response object with text:
resp = make_response('Text response')
The good thing is that within the response object it has a collection called headers in which the headers of the response go. In this way if we want to modify the headers in Flask and add a custom header we can write.
resp.headers['myheader'] = 'My Content'
Or we can overwrite some of the headers that are returned. For example we can “tune” the server header in the following way:
resp.headers['Server'] = 'My Server'
We will only have to return the response object as a result of the method:
@app.route('/')
def helloworld():
resp = make_response('Text response')
resp.headers['Server'] = 'My Server'
return resp
We have already seen how easy it is to manage headers in Flask.
