Debian Codegraph @

docs/usage/applications.rst

raw
1 Applications
2 =============
3
4 Application objects
5 -------------------
6
7 At the root of every Litestar application is an instance of the :class:`~litestar.app.Litestar`
8 class. Typically, this code will be placed in a file called ``main.py``, ``app.py``, ``asgi.py`` or similar
9 at the project's root directory.
10
11 These entry points are also used during :ref:`CLI autodiscovery <usage/cli:autodiscovery>`
12
13 Creating an app is straightforward – the only required :term:`args <argument>` is a :class:`list`
14 of :class:`Controllers <.controller.Controller>`, :class:`Routers <.router.Router>`,
15 or :class:`Route handlers <.handlers.BaseRouteHandler>`:
16
17 .. literalinclude:: /examples/hello_world.py
18 :language: python
19 :caption: A simple Hello World Litestar app
20
21 The app instance is the root level of the app - it has the base path of ``/`` and all root level
22 :class:`Controllers <.controller.Controller>`, :class:`Routers <.router.Router>`,
23 and :class:`Route handlers <.handlers.BaseRouteHandler>` should be registered on it.
24
25 .. seealso:: To learn more about registering routes, check out this chapter in the documentation:
26
27 * :ref:`Routing - Registering Routes <usage/routing/overview:Registering Routes>`
28
29 Startup and Shutdown
30 --------------------
31
32 You can pass a list of :term:`callables <python:callable>` - either sync or async functions, methods, or class instances
33 - to the :paramref:`~litestar.app.Litestar.on_startup` / :paramref:`~litestar.app.Litestar.on_shutdown`
34 :term:`kwargs <argument>` of the :class:`app <litestar.app.Litestar>` instance. Those will be called in
35 order, once the ASGI server such as `uvicorn <https://www.uvicorn.org/>`_,
36 `Hypercorn <https://hypercorn.readthedocs.io/en/latest/#/>`_, `Granian <https://github.com/emmett-framework/granian/>`_,
37 `Daphne <https://github.com/django/daphne/>`_, etc. emits the respective event.
38
39 .. mermaid::
40
41 flowchart LR
42 Startup[ASGI-Event: lifespan.startup] --> on_startup
43 Shutdown[ASGI-Event: lifespan.shutdown] --> on_shutdown
44
45 A classic use case for this is database connectivity. Often, we want to establish a database connection on application
46 startup, and then close it gracefully upon shutdown.
47
48 For example, let us create a database connection using the async engine from
49 `SQLAlchemy <https://docs.sqlalchemy.org/en/latest/orm/extensions/asyncio.html>`_. We create two functions, one to get or
50 establish the connection, and another to close it, and then pass them to the :class:`~litestar.app.Litestar` constructor:
51
52 .. literalinclude:: /examples/startup_and_shutdown.py
53 :language: python
54 :caption: Startup and Shutdown
55
56 .. _lifespan-context-managers:
57
58 Lifespan context managers
59 -------------------------
60
61 In addition to the lifespan hooks, Litestar also supports managing the lifespan of an application using an
62 :term:`asynchronous context manager`. This can be useful when dealing with long running tasks, or those that need to
63 keep a certain context object, such as a connection, around.
64
65 .. literalinclude:: /examples/application_hooks/lifespan_manager.py
66 :language: python
67 :caption: Handling a database connection
68
69 Order of execution
70 ------------------
71
72 When multiple lifespan context managers and :paramref:`~litestar.app.Litestar.on_shutdown` hooks are specified,
73 Litestar will invoke the :term:`context managers <asynchronous context manager>` in inverse order before the
74 shutdown hooks are invoked.
75
76 Consider the case where there are two lifespan context managers ``ctx_a`` and ``ctx_b`` as well as two shutdown hooks
77 ``hook_a`` and ``hook_b`` as shown in the following code:
78
79 .. code-block:: python
80 :caption: Example of multiple :term:`context managers <asynchronous context manager>` and shutdown hooks
81
82 app = Litestar(lifespan=[ctx_a, ctx_b], on_shutdown=[hook_a, hook_b])
83
84 During shutdown, they are executed in the following order:
85
86 .. mermaid::
87
88 flowchart LR
89 ctx_b --> ctx_a --> hook_a --> hook_b
90
91 As seen, the :term:`context managers <asynchronous context manager>` are invoked in inverse order.
92 On the other hand, the shutdown hooks are invoked in their specified order.
93
94 .. _application-state:
95
96 Using Application State
97 -----------------------
98
99 As seen in the examples for the `on_startup / on_shutdown <#startup-and-shutdown>`_, :term:`callables <python:callable>`
100 passed to these hooks can receive an optional :term:`kwarg <argument>` called ``app``, through which the application's
101 state object and other properties can be accessed. The advantage of using application :paramref:`~.app.Litestar.state`,
102 is that it can be accessed during multiple stages of the connection, and it can be injected into dependencies and
103 route handlers.
104
105 The Application State is an instance of the :class:`.datastructures.state.State` datastructure, and it is
106 accessible via the :paramref:`~.app.Litestar.state` attribute. As such it can be accessed wherever the app instance
107 is accessible.
108
109 :paramref:`~.app.Litestar.state` is one of the
110 :ref:`reserved keyword arguments <usage/routing/handlers:"reserved" keyword arguments>`.
111
112 It is important to understand in this context that the application instance is injected into the ASGI ``scope`` mapping
113 for each connection (i.e. request or websocket connection) as ``scope["litestar_app"]``, and can be retrieved using
114 :meth:`~.Litestar.from_scope`. This makes the application accessible wherever the scope mapping is available,
115 e.g. in middleware, on :class:`~.connection.request.Request` and :class:`~.connection.websocket.WebSocket` instances
116 (accessible as ``request.app`` / ``socket.app``), and many other places.
117
118 Therefore, :paramref:`~.app.Litestar.state` offers an easy way to share contextual data between disparate parts
119 of the application, as seen below:
120
121 .. literalinclude:: /examples/application_state/using_application_state.py
122 :language: python
123 :caption: Using Application State
124
125 .. _Initializing Application State:
126
127 Initializing Application State
128 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
129
130 To seed application state, you can pass a :class:`~.datastructures.state.State` object to the
131 :paramref:`~.app.Litestar.state` parameter of the Litestar constructor:
132
133 .. literalinclude:: /examples/application_state/passing_initial_state.py
134 :language: python
135 :caption: Using Application State
136
137 .. note:: :class:`~.datastructures.state.State` can be initialized with a :class:`dictionary <dict>`, an instance of
138 :class:`~.datastructures.state.ImmutableState` or :class:`~.datastructures.state.State`,
139 or a :class:`list` of :class:`tuples <tuple>` containing key/value pairs.
140
141 You may instruct :class:`~.datastructures.state.State` to deep copy initialized data to prevent mutation from outside
142 the application context.
143
144 To do this, set :paramref:`~.datastructures.state.State.deep_copy` to ``True`` in the
145 :class:`~.datastructures.state.State` constructor.
146
147 Injecting Application State into Route Handlers and Dependencies
148 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
149
150 As seen in the above example, Litestar offers an easy way to inject state into route handlers and dependencies - simply
151 by specifying ``state`` as a kwarg to the handler or dependency function. For example:
152
153 .. code-block:: python
154 :caption: Accessing application :class:`~.datastructures.state.State` in a handler function
155
156 from litestar import get
157 from litestar.datastructures import State
158
159
160 @get("/")
161 def handler(state: State) -> None: ...
162
163 When using this pattern you can specify the class to use for the state object. This type is not merely for type
164 checkers, rather Litestar will instantiate a new ``state`` instance based on the type you set there.
165 This allows users to use custom classes for :class:`~.datastructures.state.State`.
166
167 While this is very powerful, it might encourage users to follow anti-patterns: it is important to emphasize that using
168 state can lead to code that is hard to reason about and bugs that are difficult to understand, due to changes in
169 different ASGI contexts. As such, this pattern should be used only when it is the best choice and in a limited fashion.
170 To discourage its use, Litestar also offers a builtin :class:`~.datastructures.state.ImmutableState` class.
171 You can use this class to type state and ensure that no mutation of state is allowed:
172
173 .. literalinclude:: /examples/application_state/using_immutable_state.py
174 :language: python
175 :caption: Using Custom State to ensure immutability
176
177 Application Hooks
178 -----------------
179
180 Litestar includes several application level hooks that allow users to run their own sync or async
181 :term:`callables <python:callable>`. While you are free to use these hooks as you see fit, the design intention
182 behind them is to allow for easy instrumentation for observability (monitoring, tracing, logging, etc.).
183
184 .. note:: All application hook kwargs detailed below receive either a single :term:`python:callable` or a :class:`list`
185 of :term:`callables <python:callable>`.
186 If a :class:`list` is provided, it is called in the order it is given.
187
188 After Exception
189 ^^^^^^^^^^^^^^^
190
191 The :paramref:`~litestar.app.Litestar.after_exception` hook takes a
192 :class:`sync or async callable <litestar.types.AfterExceptionHookHandler>` that is called with two arguments:
193 the ``exception`` that occurred and the ASGI ``scope`` of the request or websocket connection.
194
195 .. literalinclude:: /examples/application_hooks/after_exception_hook.py
196 :language: python
197 :caption: After Exception Hook
198
199 .. attention:: This hook is not meant to handle exceptions - it just receives them to allow for side effects.
200 To handle exceptions you should define :ref:`exception handlers <usage/exceptions:exception handling>`.
201
202 Before Send
203 ^^^^^^^^^^^
204
205 The :paramref:`~litestar.app.Litestar.before_send` hook takes a
206 :class:`sync or async callable <litestar.types.BeforeMessageSendHookHandler>` that is called when an ASGI message is
207 sent. The hook receives the message instance and the ASGI ``scope``.
208
209 .. literalinclude:: /examples/application_hooks/before_send_hook.py
210 :language: python
211 :caption: Before Send Hook
212
213 Initialization
214 ^^^^^^^^^^^^^^
215
216 Litestar includes a hook for intercepting the arguments passed to the
217 :class:`Litestar constructor <litestar.app.Litestar>`, before they are used to instantiate the application.
218
219 Handlers can be passed to the :paramref:`~.app.Litestar.on_app_init` parameter on construction of the application,
220 and in turn, each will receive an instance of :class:`~.config.app.AppConfig` and must return an instance of same.
221
222 This hook is useful for applying common configuration between applications, and for use by developers who may wish to
223 develop third-party application configuration systems.
224
225 .. note:: :paramref:`~.app.Litestar.on_app_init` handlers cannot be :ref:`python:async def` functions, as they are
226 called within :paramref:`~litestar.app.Litestar.__init__`, outside of an async context.
227
228 .. literalinclude:: /examples/application_hooks/on_app_init.py
229 :language: python
230 :caption: Example usage of the ``on_app_init`` hook to modify the application configuration.
231
232 .. _layered-architecture:
233
234 Layered architecture
235 --------------------
236
237 Litestar has a layered architecture compromising of 4 layers:
238
239 #. :class:`The application object <litestar.app.Litestar>`
240 #. :class:`Routers <.router.Router>`
241 #. :class:`Controllers <.controller.Controller>`
242 #. :class:`Handlers <.handlers.BaseRouteHandler>`
243
244 There are many :term:`parameters <parameter>` that can be defined on every layer, in which case the :term:`parameter`
245 defined on the layer **closest to the handler** takes precedence. This allows for maximum
246 flexibility and simplicity when configuring complex applications and enables transparent
247 overriding of parameters.
248
249 Parameters that support layering are:
250
251 * :ref:`after_request <after_request>`
252 * :ref:`after_response <after_response>`
253 * :ref:`before_request <before_request>`
254 * :ref:`cache_control <usage/responses:cache control>`
255 * :doc:`dependencies </usage/dependency-injection>`
256 * :doc:`dto </usage/dto/0-basic-use>`
257 * :ref:`etag <usage/responses:etag>`
258 * :doc:`exception_handlers </usage/exceptions>`
259 * :doc:`guards </usage/security/guards>`
260 * :ref:`include_in_schema <usage/openapi/schema_generation:configuring schema generation on a route handler>`
261 * :doc:`middleware </usage/middleware/index>`
262 * :ref:`opt <handler_opts>`
263 * :ref:`request_class <usage/requests:custom request>`
264 * :ref:`response_class <usage/responses:custom responses>`
265 * :ref:`response_cookies <usage/responses:setting response cookies>`
266 * :ref:`response_headers <usage/responses:setting response headers>`
267 * :doc:`return_dto </usage/dto/0-basic-use>`
268 * ``security``
269 * ``tags``
270 * :doc:`type_decoders </usage/custom-types>`
271 * :doc:`type_encoders </usage/custom-types>`
272 * :ref:`websocket_class <usage/websockets:custom websocket>`