Python Flask Responses

Python Flask Responses

Flask Responses

When Flask invokes a view function, it expects its return value to be the response to the request. In most cases, the response is a simple string that is sent back to the client as an HTML page.When a view function needs to respond with a different status code, it can add the numeric code as a second return value after the response text. For example, the following view function returns a 400 status code, the code for a bad request error:


Responses returned by view functions can also take a third argument, a dictionary of headers that are added to the HTTP response. Instead of returning one, two, or three values as a tuple, Flask view functions have the option of returning a Response object. The make_response() function takes one, two, or three arguments, the same values that can be returned from a view function, and returns a Response object

There is a special type of response called a redirect. This response does not include a page document; it just gives the browser a new URL from which to load a new page.

A redirect is typically indicated with a 302 response status code and the URL to redirect to given in a Location header. A redirect response can be generated using a three-value return, or also with a Response object, but given its frequent use, Flask provides a redirect() helper function that creates this response:

Another special response is issued with the abort function, which is used for error handling. The following example returns status code 404 if the id dynamic argument given in the URL does not represent a valid-user