Flask - How a Request is Handled
Request Flow
- WSGI server calls the Flask object.
Flask.wsgi_app() - A
RequestContext,AppContextis created. This converts the WSGIenvirondict into aRequestobject. - The app context is pushed -⇒
current_appandgavailable. - The
appcontext_pushedsignal is sent. - The request context is pushed -⇒
requestandsessionavailable. - 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_startedsignal 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
Responseobject. - 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_finishedsignal is sent. - With exception, those handled now, with status code, response, … The
got_request_exceptionsignal 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_downsignal is sent. - The request context is popped,
requestandsessionare no longer available. - Any
teardown_appcontext()decorated functions are called. - The
appcontext_tearing_downsignal is sent. - The app context is popped,
current_appandgare no longer available. - The
appcontext_poppedsignal is sent.
Questions
- Where is signal sent?
Links
-
The app context is popped,
current_appandgare no longer available. -
The
appcontext_poppedsignal is sent.