Flask - How a Request is Handled
Request Flow
- WSGI server calls the Flask object.
Flask.wsgi_app()
- A
RequestContext
,AppContext
is created. This converts the WSGIenviron
dict into aRequest
object. - The app context is pushed -⇒
current_app
andg
available. - The
appcontext_pushed
signal is sent. - The request context is pushed -⇒
request
andsession
available. - Load existing session data using app’s
session_interface
- Check URL matched with
route()
decorator. If not match (404, 405, ..) is stored to be handled later. - The
request_started
signal is sent. - Any
url_value_preprocessor()
decorated functions are called. - Any
before_request()
decorated functions are called. - If no URL match (above), raised errors now.
- View function which is associated with
route()
decorated is called. - If there are any errors,
errorhandler()
decorated function is called to handle errors and return response. - Whatever response (before request function, view, error handler) is converted to a
Response
object. - Any
after_this_request()
decorated functions are called, then cleared. - Any
after_request()
decorated functions are called, which can modify the response object. - The session is saved, persisting any modified session data using the app’s
session_interface
. - The
request_finished
signal is sent. - With exception, those handled now, with status code, response, … The
got_request_exception
signal is sent. - The response object’s status, headers, and body are returned to the WSGI server.
- Any
teardown_request()
decorated functions are called. - The
request_tearing_down
signal is sent. - The request context is popped,
request
andsession
are no longer available. - Any
teardown_appcontext()
decorated functions are called. - The
appcontext_tearing_down
signal is sent. - The app context is popped,
current_app
andg
are no longer available. - The
appcontext_popped
signal is sent.
Questions
- Where is signal sent?
Links
-
The app context is popped,
current_app
andg
are no longer available. -
The
appcontext_popped
signal is sent.