Debian Codegraph @

docs/usage/plugins/index.rst

raw
1 .. _plugins:
2
3 =======
4 Plugins
5 =======
6
7 Litestar supports a plugin system that allows you to extend the functionality of the framework.
8
9 .. seealso::
10
11 * :doc:`/usage/databases/sqlalchemy/plugins/index`
12
13 Plugins are defined by protocols, and any type that satisfies a protocol can be included in the ``plugins`` argument of
14 the :class:`app <litestar.app.Litestar>`.
15
16
17 InitPlugin
18 ----------
19
20 ``InitPlugin`` defines an interface that allows for customization of the application's initialization process.
21 Init plugins can define dependencies, add route handlers, configure middleware, and much more!
22
23 Implementations of these plugins must define a single method:
24 :meth:`on_app_init(self, app_config: AppConfig) -> AppConfig: <litestar.plugins.InitPlugin.on_app_init>`
25
26 The method accepts and must return an :class:`AppConfig <litestar.config.app.AppConfig>` instance, which can be modified
27 and is later used to instantiate the application.
28
29 This method is invoked after any ``on_app_init`` hooks have been called, and each plugin is invoked in the order that
30 they are provided in the ``plugins`` argument of the :class:`app <litestar.app.Litestar>`. Because of this, plugin
31 authors should make it clear in their documentation if their plugin should be invoked before or after other plugins.
32
33 Example
34 +++++++
35
36 The following example shows a simple plugin that adds a route handler, and a dependency to the application.
37
38 .. literalinclude:: /examples/plugins/init_plugin_protocol.py
39 :language: python
40 :caption: ``InitPlugin`` implementation example
41
42 The ``MyPlugin`` class is an implementation of the :class:`InitPlugin <litestar.plugins.InitPlugin>`. It
43 defines a single method, ``on_app_init()``, which takes an :class:`AppConfig <litestar.config.app.AppConfig>` instance
44 as an argument and returns same.
45
46 In the ``on_app_init()`` method, the dependency mapping is updated to include a new dependency named ``"name"``, which
47 is provided by the ``get_name()`` function, and ``route_handlers`` is updated to include the ``route_handler()``
48 function. The modified :class:`AppConfig <litestar.config.app.AppConfig>` instance is then returned.
49
50 SerializationPluginProtocol
51 ---------------------------
52
53 The SerializationPluginProtocol defines a contract for plugins that provide serialization functionality for data types
54 that are otherwise unsupported by the framework.
55
56 Implementations of these plugins must define the following methods.
57
58 1. :meth:`supports_type(self, field_definition: FieldDefinition) -> bool: <litestar.plugins.SerializationPluginProtocol>`
59
60 The method takes a :class:`FieldDefinition <litestar.typing.FieldDefinition>` instance as an argument and returns a :class:`bool`
61 indicating whether the plugin supports serialization for that type.
62
63 2. :meth:`create_dto_for_type(self, field_definition: FieldDefinition) -> type[AbstractDTO]: <litestar.plugins.SerializationPluginProtocol.create_dto_for_type>`
64
65 This method accepts a :class:`FieldDefinition <litestar.typing.FieldDefinition>` instance as an argument and must return a
66 :class:`AbstractDTO <litestar.dto.base_dto.AbstractDTO>` implementation that can be used to serialize and deserialize
67 the type.
68
69 During application startup, if a data or return annotation is encountered that is not a supported type, is supported by
70 the plugin, and doesn't otherwise have a ``dto`` or ``return_dto`` defined, the plugin is used to create a DTO type for
71 that annotation.
72
73 Example
74 +++++++
75
76 The following example shows the actual implementation of the ``SerializationPluginProtocol`` for
77 `SQLAlchemy <https://www.sqlalchemy.org/>`_ models that is is provided in ``advanced_alchemy``.
78
79 .. literalinclude:: ../../../litestar/contrib/sqlalchemy/plugins/serialization.py
80 :language: python
81 :caption: ``SerializationPluginProtocol`` implementation example
82
83 :meth:`supports_type(self, field_definition: FieldDefinition) -> bool: <advanced_alchemy.extensions.litestar.SQLAlchemySerializationPlugin.supports_type>`
84 returns a :class:`bool` indicating whether the plugin supports serialization for the given type. Specifically, we return
85 ``True`` if the parsed type is either a collection of SQLAlchemy models or a single SQLAlchemy model.
86
87 :meth:`create_dto_for_type(self, field_definition: FieldDefinition) -> type[AbstractDTO]: <advanced_alchemy.extensions.litestar.SQLAlchemySerializationPlugin.create_dto_for_type>`
88 takes a :class:`FieldDefinition <litestar.typing.FieldDefinition>` instance as an argument and returns a
89 :class:`SQLAlchemyDTO <advanced_alchemy.extensions.litestar.dto.SQLAlchemyDTO>` subclass and includes some logic that may be
90 interesting to potential serialization plugin authors.
91
92 The first thing the method does is check if the parsed type is a collection of SQLAlchemy models or a single SQLAlchemy
93 model, retrieves the model type in either case and assigns it to the ``annotation`` variable.
94
95 The method then checks if ``annotation`` is already in the ``_type_dto_map`` dictionary. If it is, it returns the
96 corresponding DTO type. This is done to ensure that multiple :class:`SQLAlchemyDTO <advanced_alchemy.extensions.litestar.dto.SQLAlchemyDTO>`
97 subtypes are not created for the same model.
98
99 If the annotation is not in the ``_type_dto_map`` dictionary, the method creates a new DTO type for the annotation,
100 adds it to the ``_type_dto_map`` dictionary, and returns it.
101
102
103 DIPlugin
104 --------
105
106 :class:`~litestar.plugins.DIPlugin` can be used to extend Litestar's dependency
107 injection by providing information about injectable types.
108
109 Its main purpose it to facilitate the injection of callables with unknown signatures,
110 for example Pydantic's ``BaseModel`` classes; These are not supported natively since,
111 while they are callables, their type information is not contained within their callable
112 signature (their :func:`__init__` method).
113
114
115 .. literalinclude:: /examples/plugins/di_plugin.py
116 :language: python
117 :caption: Dynamically generating signature information for a custom type
118
119 .. toctree::
120 :titlesonly:
121
122 flash_messages
123 problem_details
124
125
126 ReceiveRoutePlugin
127 ------------------
128
129 :class:`~litestar.plugins.ReceiveRoutePlugin` allows you to receive routes as they are registered on the application.
130 This can be useful for plugins that need to perform actions based on the routes being added, such as generating
131 documentation, validating route configurations, or tracking route statistics.
132
133 Implementations of this plugin must define a single method:
134 :meth:`receive_route(self, route: BaseRoute) -> None: <litestar.plugins.ReceiveRoutePlugin.receive_route>`
135
136 The method receives a :class:`BaseRoute <litestar.routes.BaseRoute>` instance as routes are registered on the application.
137 This happens during the application initialization process, after routes are created but before the application starts.
138
139 Example
140 +++++++
141
142 The following example shows a simple plugin that logs information about each route as it's registered:
143
144 .. code-block:: python
145
146 from litestar.plugins import ReceiveRoutePlugin
147 from litestar.routes import BaseRoute
148
149 class RouteLoggerPlugin(ReceiveRoutePlugin):
150 def receive_route(self, route: BaseRoute) -> None:
151 print(f"Route registered: {route.path} [{', '.join(route.methods)}]")