Flask - How a Request is Handled

Request Flow

  1. WSGI server calls the Flask object. Flask.wsgi_app()
  2. RequestContext , AppContext is created. This converts the WSGI environ dict into a Request object.
  3. The app context is pushed - current_app and g available.
  4. The appcontext_pushed signal is sent.
  5. The request context is pushed - request and session available.
  6. Load existing session data using app’s session_interface
  7. Check URL matched with route() decorator. If not match (404, 405, ..) is stored to be handled later.
  8. The request_started signal is sent.
  9. Any url_value_preprocessor() decorated functions are called.
  10. Any before_request() decorated functions are called.
  11. If no URL match (above), raised errors now.
  12. View function which is associated with  route() decorated is called.
  13. If there are any errors,  errorhandler() decorated function is called to handle errors and return response.
  14. Whatever response (before request function, view, error handler) is converted to a Response object.
  15. Any after_this_request() decorated functions are called, then cleared.
  16. Any after_request() decorated functions are called, which can modify the response object.
  17. The session is saved, persisting any modified session data using the app’s session_interface.
  18. The request_finished signal is sent.
  19. With exception, those handled now, with status code, response, … The got_request_exception signal is sent.
  20. The response object’s status, headers, and body are returned to the WSGI server.
  21. Any teardown_request() decorated functions are called.
  22. The request_tearing_down signal is sent.
  23. The request context is popped, request and session are no longer available.
  24. Any teardown_appcontext() decorated functions are called.
  25. The appcontext_tearing_down signal is sent.
  26. The app context is popped, current_app and g are no longer available.
  27. The appcontext_popped signal is sent.

Questions

  • Where is signal sent?
  1. The app context is popped, current_app and g are no longer available.

  2. The appcontext_popped signal is sent.