fastapi-cli 0.0.28__py3-none-any.whl → 0.0.30__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fastapi_cli/__init__.py CHANGED
@@ -1 +1 @@
1
- __version__ = "0.0.28"
1
+ __version__ = "0.0.30"
fastapi_cli/cli.py CHANGED
@@ -20,7 +20,11 @@ from fastapi_cli.exceptions import FastAPICLIException
20
20
 
21
21
  from . import __version__
22
22
  from .logging import setup_logging
23
- from .utils.cli import get_rich_toolkit, get_uvicorn_log_config
23
+ from .utils.cli import (
24
+ get_rich_toolkit,
25
+ get_uvicorn_log_config,
26
+ should_use_rich_logs,
27
+ )
24
28
 
25
29
  app = typer.Typer(
26
30
  rich_markup_mode="rich", context_settings={"help_option_names": ["-h", "--help"]}
@@ -142,11 +146,12 @@ def _run(
142
146
  with get_rich_toolkit() as toolkit:
143
147
  server_type = "development" if command == "dev" else "production"
144
148
 
145
- toolkit.print_title(f"Starting {server_type} server 🚀", tag="FastAPI")
146
- toolkit.print_line()
149
+ toolkit.print(f"Starting FastAPI in {server_type} mode", emoji="⚡️")
147
150
 
151
+ toolkit.print_line()
148
152
  toolkit.print(
149
- "Searching for package file structure from directories with [blue]__init__.py[/blue] files"
153
+ "Searching for package file structure from directories with [blue]__init__.py[/blue] files",
154
+ emoji="🔎",
150
155
  )
151
156
 
152
157
  if entrypoint and (path or app):
@@ -154,7 +159,6 @@ def _run(
154
159
  toolkit.print(
155
160
  "[error]Cannot use --entrypoint together with path or --app arguments"
156
161
  )
157
- toolkit.print_line()
158
162
  raise typer.Exit(code=1)
159
163
 
160
164
  try:
@@ -168,8 +172,6 @@ def _run(
168
172
  field = ".".join(str(loc) for loc in error["loc"])
169
173
  toolkit.print(f" [red]•[/red] {field}: {error['msg']}")
170
174
 
171
- toolkit.print_line()
172
-
173
175
  raise typer.Exit(code=1) from None
174
176
 
175
177
  try:
@@ -193,45 +195,43 @@ def _run(
193
195
  module_data = import_data.module_data
194
196
  import_string = import_data.import_string
195
197
 
196
- toolkit.print(f"Importing from {module_data.extra_sys_path}")
198
+ toolkit.print_line()
199
+ toolkit.print(f"Importing from {module_data.extra_sys_path}", emoji="📂")
197
200
  toolkit.print_line()
198
201
 
199
202
  if module_data.module_paths:
200
203
  root_tree = _get_module_tree(module_data.module_paths)
201
204
 
202
- toolkit.print(root_tree, tag="module")
203
- toolkit.print_line()
205
+ toolkit.print(root_tree)
206
+
207
+ toolkit.print_line()
204
208
 
205
209
  toolkit.print(
206
210
  "Importing the FastAPI app object from the module with the following code:",
207
- tag="code",
208
211
  )
209
212
  toolkit.print_line()
210
213
  toolkit.print(
211
- f"[underline]from [bold]{module_data.module_import_str}[/bold] import [bold]{import_data.app_name}[/bold]"
214
+ f"[blue]from [bold]{module_data.module_import_str}[/bold] import [bold]{import_data.app_name}[/bold]",
212
215
  )
213
- toolkit.print_line()
214
216
 
215
- toolkit.print(
216
- f"Using import string: [blue]{import_string}[/]",
217
- tag="app",
218
- )
217
+ toolkit.print_line()
218
+ toolkit.print(f"Using import string: [blue]{import_string}[/]", emoji="🐍")
219
219
 
220
+ toolkit.print_line()
220
221
  mod_source_desc = SOURCE_DESCRIPTIONS[import_data.module_config_source]
221
222
  app_source_desc = SOURCE_DESCRIPTIONS[import_data.app_name_config_source]
222
- toolkit.print_line()
223
- toolkit.print("Configuration sources:", tag="info")
223
+ toolkit.print("Configuration sources:", emoji="📋")
224
224
  if mod_source_desc == app_source_desc:
225
- toolkit.print(f" • Import string: {mod_source_desc}")
225
+ toolkit.print(f"• Import string: {mod_source_desc}")
226
226
  else:
227
- toolkit.print(f" • Module: {mod_source_desc}")
228
- toolkit.print(f" • App name: {app_source_desc}")
227
+ toolkit.print(f"• Module: {mod_source_desc}")
228
+ toolkit.print(f"• App name: {app_source_desc}")
229
229
 
230
230
  if import_data.module_config_source == "auto-discovery":
231
231
  toolkit.print_line()
232
232
  toolkit.print(
233
233
  "You can configure an entrypoint in [blue]pyproject.toml[/] for this app with:",
234
- tag="tip",
234
+ emoji="💡",
235
235
  )
236
236
  toolkit.print_line()
237
237
  toolkit.print(
@@ -242,24 +242,21 @@ def _run(
242
242
  ),
243
243
  "toml",
244
244
  theme="ansi_light",
245
- )
245
+ ),
246
246
  )
247
247
 
248
248
  url = public_url.rstrip("/") if public_url else f"http://{host}:{port}"
249
249
  url_docs = f"{url}/docs"
250
250
 
251
251
  toolkit.print_line()
252
- toolkit.print(
253
- f"Server started at [link={url}]{url}[/]",
254
- f"Documentation at [link={url_docs}]{url_docs}[/]",
255
- tag="server",
256
- )
252
+ toolkit.print(f"Server started at [link={url}]{url}[/]", emoji="🌐")
253
+ toolkit.print(f"Documentation at [link={url_docs}]{url_docs}[/]")
257
254
 
258
255
  if command == "dev":
259
256
  toolkit.print_line()
260
257
  toolkit.print(
261
258
  "Running in development mode, for production use: [bold]fastapi run[/]",
262
- tag="tip",
259
+ emoji="💡",
263
260
  )
264
261
 
265
262
  if not uvicorn:
@@ -268,9 +265,13 @@ def _run(
268
265
  ) from None
269
266
 
270
267
  toolkit.print_line()
271
- toolkit.print("Logs:")
268
+ toolkit.print("Logs:", bullet=False)
272
269
  toolkit.print_line()
273
270
 
271
+ extra_uvicorn_kwargs: dict[str, Any] = (
272
+ {"log_config": get_uvicorn_log_config()} if should_use_rich_logs() else {}
273
+ )
274
+
274
275
  uvicorn.run(
275
276
  app=import_string,
276
277
  host=host,
@@ -285,7 +286,7 @@ def _run(
285
286
  root_path=root_path,
286
287
  proxy_headers=proxy_headers,
287
288
  forwarded_allow_ips=forwarded_allow_ips,
288
- log_config=get_uvicorn_log_config(),
289
+ **extra_uvicorn_kwargs,
289
290
  )
290
291
 
291
292
 
fastapi_cli/utils/cli.py CHANGED
@@ -1,10 +1,131 @@
1
1
  import logging
2
+ import sys
2
3
  from typing import Any
3
4
 
4
- from rich_toolkit import RichToolkit, RichToolkitTheme
5
- from rich_toolkit.styles import TaggedStyle
5
+ from rich._loop import loop_first
6
+ from rich.console import Console, ConsoleOptions, RenderableType, RenderResult
7
+ from rich.segment import Segment
8
+ from rich.text import Text
9
+ from rich_toolkit import RichToolkit
10
+ from rich_toolkit.element import Element
11
+ from rich_toolkit.styles import BaseStyle
6
12
  from uvicorn.logging import DefaultFormatter
7
13
 
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ def should_use_rich_logs() -> bool:
18
+ """Return True when stdout is a TTY and rich logs should be used, False otherwise."""
19
+ return sys.stdout.isatty()
20
+
21
+
22
+ class IndentedBlock:
23
+ """Indent a renderable, hanging a prefix (e.g. an emoji bullet) on the
24
+ first line and aligning wrapped/extra lines under the text."""
25
+
26
+ def __init__(
27
+ self,
28
+ renderable: RenderableType,
29
+ *,
30
+ first_prefix: Text,
31
+ prefix: Text,
32
+ ) -> None:
33
+ self.renderable = renderable
34
+ self.first_prefix = first_prefix
35
+ self.prefix = prefix
36
+
37
+ # Text renders its `end` ("\n" by default), which would break lines
38
+ self.first_prefix.end = ""
39
+ self.prefix.end = ""
40
+
41
+ def __rich_console__(
42
+ self, console: Console, options: ConsoleOptions
43
+ ) -> RenderResult:
44
+ prefix_width = max(self.first_prefix.cell_len, self.prefix.cell_len)
45
+ lines = console.render_lines(
46
+ self.renderable,
47
+ options.update_width(options.max_width - prefix_width),
48
+ pad=False,
49
+ )
50
+
51
+ new_line = Segment.line()
52
+
53
+ for first, line in loop_first(lines):
54
+ if any(segment.text.strip() for segment in line):
55
+ yield from console.render(
56
+ self.first_prefix if first else self.prefix, options
57
+ )
58
+ yield from line
59
+
60
+ yield new_line
61
+
62
+
63
+ class FastAPIStyle(BaseStyle):
64
+ """Uniform left indent with emoji bullets hanging to the left of the text.
65
+
66
+ ``emoji=`` renders as a bullet in a fixed column; ``bullet=False`` drops
67
+ the bullet column and just indents. This is a small, purpose-built subset
68
+ of the richer style in fastapi-cloud-cli.
69
+ """
70
+
71
+ content_padding = 1
72
+ emoji_column_width = 3
73
+
74
+ def render_element(
75
+ self,
76
+ element: Any,
77
+ is_active: bool = False,
78
+ done: bool = False,
79
+ parent: Element | None = None,
80
+ **kwargs: Any,
81
+ ) -> RenderableType:
82
+ rendered = super().render_element(
83
+ element=element, is_active=is_active, done=done, parent=parent, **kwargs
84
+ )
85
+
86
+ emoji = kwargs.get("emoji", "")
87
+
88
+ if not emoji and not kwargs.get("bullet", True):
89
+ indent = Text(" " * (self.content_padding + 1))
90
+ return IndentedBlock(rendered, first_prefix=indent, prefix=indent)
91
+
92
+ return IndentedBlock(
93
+ rendered,
94
+ first_prefix=self._get_bullet_prefix(emoji),
95
+ prefix=Text(" " * (self.content_padding + self.emoji_column_width)),
96
+ )
97
+
98
+ def _get_bullet_prefix(self, emoji: str) -> Text:
99
+ prefix = Text(" " * self.content_padding)
100
+
101
+ if emoji:
102
+ prefix.append_text(Text.from_markup(emoji))
103
+
104
+ prefix.pad_right(
105
+ self.content_padding + self.emoji_column_width - prefix.cell_len
106
+ )
107
+
108
+ return prefix
109
+
110
+
111
+ LOG_LEVEL_COLORS = {
112
+ "debug": "blue",
113
+ "info": "cyan",
114
+ "warning": "yellow",
115
+ "warn": "yellow",
116
+ "error": "red",
117
+ "critical": "magenta",
118
+ "fatal": "magenta",
119
+ }
120
+
121
+
122
+ def _get_log_bullet(level: str) -> str:
123
+ """Colored bar rendered in the emoji bullet column, matching the log
124
+ level, like the ``fastapi cloud logs`` output."""
125
+ color = LOG_LEVEL_COLORS.get(level.lower(), "dim")
126
+
127
+ return f"[{color}]▕[/{color}]"
128
+
8
129
 
9
130
  class CustomFormatter(DefaultFormatter):
10
131
  def __init__(self, *args: Any, **kwargs: Any) -> None:
@@ -13,7 +134,9 @@ class CustomFormatter(DefaultFormatter):
13
134
 
14
135
  def formatMessage(self, record: logging.LogRecord) -> str:
15
136
  message = record.getMessage()
16
- result = self.toolkit.print_as_string(message, tag=record.levelname)
137
+ result = self.toolkit.print_as_string(
138
+ message, emoji=_get_log_bullet(record.levelname)
139
+ )
17
140
  # Prepend newline to fix alignment after ^C is printed by the terminal
18
141
  if message == "Shutting down":
19
142
  result = "\n" + result
@@ -63,23 +186,5 @@ def get_uvicorn_log_config() -> dict[str, Any]:
63
186
  }
64
187
 
65
188
 
66
- logger = logging.getLogger(__name__)
67
-
68
-
69
189
  def get_rich_toolkit() -> RichToolkit:
70
- theme = RichToolkitTheme(
71
- style=TaggedStyle(tag_width=11),
72
- theme={
73
- "tag.title": "white on #009485",
74
- "tag": "white on #007166",
75
- "placeholder": "grey85",
76
- "text": "white",
77
- "selected": "#007166",
78
- "result": "grey85",
79
- "progress": "on #007166",
80
- "error": "red",
81
- "log.info": "black on blue",
82
- },
83
- )
84
-
85
- return RichToolkit(theme=theme)
190
+ return RichToolkit(style=FastAPIStyle())
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fastapi-cli
3
- Version: 0.0.28
3
+ Version: 0.0.30
4
4
  Summary: Run and manage FastAPI apps from the command line with FastAPI CLI. 🚀
5
5
  Author-Email: =?utf-8?q?Sebasti=C3=A1n_Ram=C3=ADrez?= <tiangolo@gmail.com>
6
6
  License-Expression: MIT
@@ -1,15 +1,15 @@
1
- fastapi_cli-0.0.28.dist-info/METADATA,sha256=DGd1vh_9xRMnfYrNnYn49HHRlcWL8IV6VcruUJRDLqg,6190
2
- fastapi_cli-0.0.28.dist-info/WHEEL,sha256=VP-D4TPS230sME9Z3vb3INXvo1yt0924YRm5AOsk_dE,90
3
- fastapi_cli-0.0.28.dist-info/entry_points.txt,sha256=6OYgBcLyFCUgeqLgnvMyOJxPCWzgy7se4rLPKtNonMs,34
4
- fastapi_cli-0.0.28.dist-info/licenses/LICENSE,sha256=FqD5B4VbXJnefprQseE0U8llL6FxojC-i8muZy7YmSU,1086
5
- fastapi_cli/__init__.py,sha256=OxG64Q6SDQQGNb5ggPOgDkHI0rY-RjCF92VCMUiyhOQ,23
1
+ fastapi_cli-0.0.30.dist-info/METADATA,sha256=mxaPksaNiovpDoheBCpo9HzRrv3kg6bcExeRA8XIT1g,6190
2
+ fastapi_cli-0.0.30.dist-info/WHEEL,sha256=VP-D4TPS230sME9Z3vb3INXvo1yt0924YRm5AOsk_dE,90
3
+ fastapi_cli-0.0.30.dist-info/entry_points.txt,sha256=6OYgBcLyFCUgeqLgnvMyOJxPCWzgy7se4rLPKtNonMs,34
4
+ fastapi_cli-0.0.30.dist-info/licenses/LICENSE,sha256=FqD5B4VbXJnefprQseE0U8llL6FxojC-i8muZy7YmSU,1086
5
+ fastapi_cli/__init__.py,sha256=8ZeepqkW4DvpVeNm92mx0tIzgvVevS4NKWkTXXHuXNY,23
6
6
  fastapi_cli/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30
7
- fastapi_cli/cli.py,sha256=Sa_bd9QmM3FKRZWVrDgmbWZ92xrMtmJtsNm0vYUKoLE,16944
7
+ fastapi_cli/cli.py,sha256=y7Lz5JuOSCPLnxXgGvREs2nWCPtCAPh3s4o96dppUPY,17037
8
8
  fastapi_cli/config.py,sha256=o-yPktLddeMGSX25VjOg3W8I-jidDF9SQccpPpwpQt4,1463
9
9
  fastapi_cli/discover.py,sha256=dXH63dQ_bKLF0GQFIxWfHKDhTyFZWBpkyzPyoLLCSko,5472
10
10
  fastapi_cli/exceptions.py,sha256=AHRSqd43fbqN5IpX-Fq389k9MoEK_q28wVFL7oqPNcc,47
11
11
  fastapi_cli/logging.py,sha256=_gMopiUSunAhBT7nuafiVLeQV-hEmswPifV_l16tpH4,653
12
12
  fastapi_cli/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
13
  fastapi_cli/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
- fastapi_cli/utils/cli.py,sha256=pr1vL9VXhw9PUj2W1xirPfJvNsNvYfCgowFnniFTbHo,2548
15
- fastapi_cli-0.0.28.dist-info/RECORD,,
14
+ fastapi_cli/utils/cli.py,sha256=qH_DXQahKpWF3Zara_E_6YVuaz30ztVch0dQAJoXRVY,5702
15
+ fastapi_cli-0.0.30.dist-info/RECORD,,