Skip to content
Myr

lifecycle.rst

This file

Path

docs/lifecycle.rst

171 lines · 8.8 KiB

Last changed by

merge app and request context (#5812)David Lordbefore adoptionadf3636

History of this file

Take it

The walk stopped after 200 commits: lines older than 9659b11 point at it.

remove pypy 3.8 and 3.7 from testsDavid Lordbefore adoption9659b11

lines 1–119why, one step back
1Application Structure and Lifecycle
2===================================34Flask makes it pretty easy to write a web application. But there are quite a few5different parts to an application and to each request it handles. Knowing what happens6during application setup, serving, and handling requests will help you know what's7possible in Flask and how to structure your application.8910Application Setup11-----------------1213The first step in creating a Flask application is creating the application object. Each14Flask application is an instance of the :class:`.Flask` class, which collects all15configuration, extensions, and views.1617.. code-block:: python1819 from flask import Flask2021 app = Flask(__name__)22 app.config.from_mapping(23 SECRET_KEY="dev",24 )25 app.config.from_prefixed_env()2627 @app.route("/")28 def index():29 return "Hello, World!"3031This is known as the "application setup phase", it's the code you write that's outside32any view functions or other handlers. It can be split up between different modules and33sub-packages, but all code that you want to be part of your application must be imported34in order for it to be registered.3536All application setup must be completed before you start serving your application and37handling requests. This is because WSGI servers divide work between multiple workers, or38can be distributed across multiple machines. If the configuration changed in one worker,39there's no way for Flask to ensure consistency between other workers.4041Flask tries to help developers catch some of these setup ordering issues by showing an42error if setup-related methods are called after requests are handled. In that case43you'll see this error:4445 The setup method 'route' can no longer be called on the application. It has already46 handled its first request, any changes will not be applied consistently.47 Make sure all imports, decorators, functions, etc. needed to set up the application48 are done before running it.4950However, it is not possible for Flask to detect all cases of out-of-order setup. In51general, don't do anything to modify the ``Flask`` app object and ``Blueprint`` objects52from within view functions that run during requests. This includes:5354- Adding routes, view functions, and other request handlers with ``@app.route``,55 ``@app.errorhandler``, ``@app.before_request``, etc.56- Registering blueprints.57- Loading configuration with ``app.config``.58- Setting up the Jinja template environment with ``app.jinja_env``.59- Setting a session interface, instead of the default itsdangerous cookie.60- Setting a JSON provider with ``app.json``, instead of the default provider.61- Creating and initializing Flask extensions.626364Serving the Application65-----------------------6667Flask is a WSGI application framework. The other half of WSGI is the WSGI server. During68development, Flask, through Werkzeug, provides a development WSGI server with the69``flask run`` CLI command. When you are done with development, use a production server70to serve your application, see :doc:`deploying/index`.7172Regardless of what server you're using, it will follow the :pep:`3333` WSGI spec. The73WSGI server will be told how to access your Flask application object, which is the WSGI74application. Then it will start listening for HTTP requests, translate the request data75into a WSGI environ, and call the WSGI application with that data. The WSGI application76will return data that is translated into an HTTP response.7778#. Browser or other client makes HTTP request.79#. WSGI server receives request.80#. WSGI server converts HTTP data to WSGI ``environ`` dict.81#. WSGI server calls WSGI application with the ``environ``.82#. Flask, the WSGI application, does all its internal processing to route the request83 to a view function, handle errors, etc.84#. Flask translates View function return into WSGI response data, passes it to WSGI85 server.86#. WSGI server creates and send an HTTP response.87#. Client receives the HTTP response.888990Middleware91~~~~~~~~~~9293The WSGI application above is a callable that behaves in a certain way. Middleware94is a WSGI application that wraps another WSGI application. It's a similar concept to95Python decorators. The outermost middleware will be called by the server. It can modify96the data passed to it, then call the WSGI application (or further middleware) that it97wraps, and so on. And it can take the return value of that call and modify it further.9899From the WSGI server's perspective, there is one WSGI application, the one it calls100directly. Typically, Flask is the "real" application at the end of the chain of101middleware. But even Flask can call further WSGI applications, although that's an102advanced, uncommon use case.103104A common middleware you'll see used with Flask is Werkzeug's105:class:`~werkzeug.middleware.proxy_fix.ProxyFix`, which modifies the request to look106like it came directly from a client even if it passed through HTTP proxies on the way.107There are other middleware that can handle serving static files, authentication, etc.108109110How a Request is Handled111------------------------112113For us, the interesting part of the steps above is when Flask gets called by the WSGI114server (or middleware). At that point, it will do quite a lot to handle the request and115generate the response. At the most basic, it will match the URL to a view function, call116the view function, and pass the return value back to the server. But there are many more117parts that you can use to customize its behavior.118119#. WSGI server calls the Flask object, which calls :meth:`.Flask.wsgi_app`.

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 120–124why, one step back
120#. An :class:`.AppContext` object is created. This converts the WSGI ``environ``
121 dict into a :class:`.Request` object.122#. The :doc:`app context <appcontext>` is pushed, which makes123 :data:`.current_app`, :data:`.g`, :data:`.request`, and :data:`.session`124 available.

remove pypy 3.8 and 3.7 from testsDavid Lordbefore adoption9659b11

lines 125–140why, one step back
125#. The :data:`.appcontext_pushed` signal is sent.
126#. The URL is matched against the URL rules registered with the :meth:`~.Flask.route`127 decorator during application setup. If there is no match, the error - usually a 404,128 405, or redirect - is stored to be handled later.129#. The :data:`.request_started` signal is sent.130#. Any :meth:`~.Flask.url_value_preprocessor` decorated functions are called.131#. Any :meth:`~.Flask.before_request` decorated functions are called. If any of132 these function returns a value it is treated as the response immediately.133#. If the URL didn't match a route a few steps ago, that error is raised now.134#. The :meth:`~.Flask.route` decorated view function associated with the matched URL135 is called and returns a value to be used as the response.136#. If any step so far raised an exception, and there is an :meth:`~.Flask.errorhandler`137 decorated function that matches the exception class or HTTP error code, it is138 called to handle the error and return a response.139#. Whatever returned a response value - a before request function, the view, or an140 error handler, that value is converted to a :class:`.Response` object.

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 141–142why, one step back
141#. Any :func:`~.after_this_request` decorated functions are called, which can modify
142 the response object. They are then cleared.

remove pypy 3.8 and 3.7 from testsDavid Lordbefore adoption9659b11

lines 143–156why, one step back
143#. Any :meth:`~.Flask.after_request` decorated functions are called, which can modify
144 the response object.145#. The session is saved, persisting any modified session data using the app's146 :attr:`~.Flask.session_interface`.147#. The :data:`.request_finished` signal is sent.148#. If any step so far raised an exception, and it was not handled by an error handler149 function, it is handled now. HTTP exceptions are treated as responses with their150 corresponding status code, other exceptions are converted to a generic 500 response.151 The :data:`.got_request_exception` signal is sent.152#. The response object's status, headers, and body are returned to the WSGI server.153#. Any :meth:`~.Flask.teardown_request` decorated functions are called.154#. The :data:`.request_tearing_down` signal is sent.155#. Any :meth:`~.Flask.teardown_appcontext` decorated functions are called.156#. The :data:`.appcontext_tearing_down` signal is sent.

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 157–158why, one step back
157#. The app context is popped, :data:`.current_app`, :data:`.g`, :data:`.request`,
158 and :data:`.session` are no longer available.

remove pypy 3.8 and 3.7 from testsDavid Lordbefore adoption9659b11

line 159why, one step back
159#. The :data:`.appcontext_popped` signal is sent.

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 160–166why, one step back
160
161When executing a CLI command or plain app context without request data, the same162order of steps is followed, omitting the steps that refer to the request.163164A :class:`Blueprint` can add handlers for these events that are specific to the165blueprint. The handlers for a blueprint will run if the blueprint166owns the route that matches the request.

remove pypy 3.8 and 3.7 from testsDavid Lordbefore adoption9659b11

lines 167–171why, one step back
167
168There are even more decorators and customization points than this, but that aren't part169of every request lifecycle. They're more specific to certain things you might use during170a request, such as templates, building URLs, or handling JSON data. See the rest of this171documentation, as well as the :doc:`api` to explore further.