Debian Codegraph @

docs/usage/cli.rst

raw
1 CLI
2 ===
3
4 .. |uvicorn| replace:: uvicorn
5 .. _uvicorn: https://www.uvicorn.org/
6
7 Litestar provides a convenient command line interface (CLI) for running and managing Litestar applications. The CLI is
8 powered by `click <https://click.palletsprojects.com/>`_, `rich <https://rich.readthedocs.io>`_,
9 and `rich-click <https://github.com/ewels/rich-click>`_.
10
11 Enabling all CLI features
12 -------------------------
13
14 The CLI and its hard dependencies are included by default. However, if you want to run your application
15 (using ``litestar run`` ) or beautify the Typescript generated by the ``litestar schema typescript``
16 command, you will need |uvicorn|_ and `jsbeautifier <https://pypi.org/project/jsbeautifier/>`_.
17 They can be installed independently, but we recommend installing the ``standard`` extra which conveniently bundles
18 commonly used optional dependencies.
19
20 .. code-block:: shell
21 :caption: Install the standard group
22
23 pip install 'litestar[standard]'
24
25 Once you have installed ``standard``, you will have access to the ``litestar run`` command.
26
27 Autodiscovery
28 -------------
29
30 Litestar offers autodiscovery of applications and application factories placed within the canonical modules named
31 either ``app`` or ``application``. These modules can be individual files or directories. Within these modules or their
32 submodules, the CLI will detect any instances of :class:`Litestar <.app.Litestar>`, callables named ``create_app``, or
33 callables annotated to return a :class:`Litestar <.app.Litestar>` instance.
34
35 The autodiscovery follows these lookup locations in order:
36
37 1. ``app.py``
38 2. ``app/__init__.py``
39 3. Submodules of ``app``
40 4. ``application.py``
41 5. ``application/__init__.py``
42 6. Submodules of ``application``
43
44 Within these locations, Litestar CLI looks for:
45
46 1. An :term:`object` named ``app`` that is an instance of :class:`~.app.Litestar`
47 2. An object named ``application`` that is an instance of :class:`~.app.Litestar`
48 3. Any object that is an instance of :class:`~.app.Litestar`
49 4. A :term:`callable` named ``create_app``
50 5. A callable annotated to return an instance of :class:`~.app.Litestar`
51
52 Specifying an application explicitly
53 ------------------------------------
54
55 The application to be used can be specified explicitly via either the ``--app`` argument
56 or the ``LITESTAR_APP`` environment variable. The format for both of them is
57 ``<module name>.<submodule>:<app instance or factory>``.
58
59 When both ``--app`` and ``LITESTAR_APP`` are set, the CLI option takes precedence over
60 the environment variable.
61
62
63 .. code-block:: bash
64 :caption: Using 'litestar run' and specifying an application factory via --app
65
66 litestar --app=my_application.app:create_my_app run
67
68
69 .. code-block:: bash
70 :caption: Using 'litestar run' and specifying an application factory via LITESTAR_APP
71
72 LITESTAR_APP=my_application.app:create_my_app litestar run
73
74
75
76 Extending the CLI
77 -----------------
78
79 Litestar's CLI is built with `click <https://click.palletsprojects.com/>`_ and can be extended by making use of
80 `entry points <https://packaging.python.org/en/latest/specifications/entry-points/>`_,
81 or by creating a plugin that conforms to the :class:`~.plugins.CLIPluginProtocol`.
82
83 Using entry points
84 ^^^^^^^^^^^^^^^^^^
85
86 Entry points for the CLI can be added under the ``litestar.commands`` group. These
87 entries should point to a :class:`click.Command` or :class:`click.Group`:
88
89 .. tab-set::
90
91 .. tab-item:: setup.py
92
93 .. code-block:: python
94 :caption: Using `setuptools <https://setuptools.pypa.io/en/latest/>`_
95
96 from setuptools import setup
97
98 setup(
99 name="my-litestar-plugin",
100 ...,
101 entry_points={
102 "litestar.commands": ["my_command=my_litestar_plugin.cli:main"],
103 },
104 )
105
106 .. tab-item:: pdm
107
108 .. code-block:: toml
109 :caption: Using `PDM <https://pdm.fming.dev/>`_
110
111 [project.scripts]
112 my_command = "my_litestar_plugin.cli:main"
113
114 # Or, as an entrypoint:
115
116 [project.entry-points."litestar.commands"]
117 my_command = "my_litestar_plugin.cli:main"
118
119 .. tab-item:: poetry
120
121 .. code-block:: toml
122 :caption: Using `poetry <https://python-poetry.org/>`_
123
124 [project.entry-points."litestar.commands"]
125 my_command = "my_litestar_plugin.cli:main"
126
127 .. tab-item:: uv
128
129 .. code-block:: toml
130 :caption: Using `uv <https://docs.astral.sh/uv/>`_
131
132 [project.entry-points."litestar.commands"]
133 my_command = "my_litestar_plugin.cli:main"
134
135 Using a plugin
136 ^^^^^^^^^^^^^^
137
138 A plugin extending the CLI can be created using the :class:`~.plugins.CLIPluginProtocol`.
139 Its :meth:`~.plugins.CLIPluginProtocol.on_cli_init` will be called during the initialization of the CLI,
140 and receive the root :class:`click.Group` as its first argument, which can then be used to add or override commands:
141
142 .. code-block:: python
143 :caption: Creating a CLI plugin
144
145 from litestar import Litestar
146 from litestar.plugins import CLIPluginProtocol
147 from click import Group
148
149
150 class CLIPlugin(CLIPluginProtocol):
151 def on_cli_init(self, cli: Group) -> None:
152 @cli.command()
153 def is_debug_mode(app: Litestar):
154 print(app.debug)
155
156
157 app = Litestar(plugins=[CLIPlugin()])
158
159 Accessing the app instance
160 ^^^^^^^^^^^^^^^^^^^^^^^^^^
161
162 When extending the Litestar CLI, you will most likely need access to the loaded ``Litestar`` instance.
163 You can achieve this by adding the special ``app`` parameter to your CLI functions. This will cause the
164 ``Litestar`` instance to be injected into the function whenever it is called from a click-context.
165
166 .. code-block:: python
167 :caption: Accessing the app instance programmatically
168
169 import click
170 from litestar import Litestar
171
172
173 @click.command()
174 def my_command(app: Litestar) -> None: ...
175
176 Using the `server_lifespan` hook
177 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
178
179 Server lifespan hooks provide a way to run code before and after the *server* starts and stops. In contrast to the regular `lifespan` hooks, they only run once, even when a server starts multiple workers, whereas `lifespan` hooks would run for each individual worker.
180
181 This makes them suitable for tasks that should happen exactly once, like initializing a database.
182
183 .. code-block:: python
184 :caption: Using the `server_lifespan` hook
185
186 from contextlib import contextmanager
187 from typing import Generator
188
189 from litestar import Litestar
190 from litestar.config.app import AppConfig
191 from litestar.plugins.base import CLIPlugin
192
193
194 class StartupPrintPlugin(CLIPlugin):
195
196 @contextmanager
197 def server_lifespan(self, app: Litestar) -> Generator[None, None, None]:
198 print("i_run_before_startup_plugin") # noqa: T201
199 try:
200 yield
201 finally:
202 print("i_run_after_shutdown_plugin") # noqa: T201
203
204 def create_app() -> Litestar:
205 return Litestar(route_handlers=[], plugins=[StartupPrintPlugin()])
206
207
208 CLI Reference
209 -------------
210
211 The most up-to-date reference for the Litestar CLI can be found by running:
212
213 .. code-block:: shell
214 :caption: Display the CLI help
215
216 litestar --help
217
218 You can also visit the :doc:`Litestar CLI Click API Reference </reference/cli>` for that same
219 information.