Python Flask Request-Response Cycle














































Python Flask Request-Response Cycle



Flask Request-Response Cycle


When Flask receives a request from a client, it needs to make a few objects available to the view function that will handle it. A good example is the request object, which encapsulates the HTTP request sent by the client.




Output



Note how in this view function request is used as if it was a global variable. In reality, the request cannot be a global variable if you consider that in a multithreaded server the threads are working on different requests from different clients at the same time, so each thread needs to see a different object in request. Contexts enable Flask to make certain variables globally accessible to a thread without interfering with the other threads.


Flask activates (or pushes) the application and request contexts before dispatching a request and then remove them when the request is handled. When the application context is  pushed, the current_app and g variables become available to the thread; likewise, when the request context is pushed, request and session become available as well


In this example, current_app.name fails when there is no application context active but becomes valid once a context is pushed. Note how an application context is obtained by invoking app.app_context() on the application instance.


Request Dispatching 

When the application receives a request from a client, it needs to find what view function to invoke to service it. For this task, Flask looks up the URL given in the request in the applications URL map, which contains a mapping of URLs to the view functions that handle them. Flask builds this map using the app.route decorators or the equivalent nondecorator version app.add_url_rule().



The / and /user/ routes were defined by the app.route decorators in the application. The /static/ route is a special route added by Flask to give access to static files

The HEAD, OPTIONS, GET elements shown in the URL map are the request methods that are handled by the route. Flask attaches methods to each route so that different request methods sent to the same URL can be handled by different view functions. The HEAD and OPTIONS methods are managed automatically by Flask






Comments