Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 

359 righe
11 KiB

  1. import logging
  2. from pathlib import Path
  3. from typing import Any, List, Union
  4. import typer
  5. from rich import print
  6. from rich.tree import Tree
  7. from typing_extensions import Annotated
  8. from fastapi_cli.discover import get_import_data
  9. from fastapi_cli.exceptions import FastAPICLIException
  10. from . import __version__
  11. from .logging import setup_logging
  12. from .utils.cli import get_rich_toolkit, get_uvicorn_log_config
  13. app = typer.Typer(rich_markup_mode="rich")
  14. logger = logging.getLogger(__name__)
  15. try:
  16. import uvicorn
  17. except ImportError: # pragma: no cover
  18. uvicorn = None # type: ignore[assignment]
  19. try:
  20. from fastapi_cloud_cli.cli import (
  21. app as fastapi_cloud_cli,
  22. )
  23. app.add_typer(fastapi_cloud_cli)
  24. except ImportError: # pragma: no cover
  25. pass
  26. def version_callback(value: bool) -> None:
  27. if value:
  28. print(f"FastAPI CLI version: [green]{__version__}[/green]")
  29. raise typer.Exit()
  30. @app.callback()
  31. def callback(
  32. version: Annotated[
  33. Union[bool, None],
  34. typer.Option(
  35. "--version", help="Show the version and exit.", callback=version_callback
  36. ),
  37. ] = None,
  38. verbose: bool = typer.Option(False, help="Enable verbose output"),
  39. ) -> None:
  40. """
  41. FastAPI CLI - The [bold]fastapi[/bold] command line app. 😎
  42. Manage your [bold]FastAPI[/bold] projects, run your FastAPI apps, and more.
  43. Read more in the docs: [link=https://fastapi.tiangolo.com/fastapi-cli/]https://fastapi.tiangolo.com/fastapi-cli/[/link].
  44. """
  45. log_level = logging.DEBUG if verbose else logging.INFO
  46. setup_logging(level=log_level)
  47. def _get_module_tree(module_paths: List[Path]) -> Tree:
  48. root = module_paths[0]
  49. name = f"🐍 {root.name}" if root.is_file() else f"📁 {root.name}"
  50. root_tree = Tree(name)
  51. if root.is_dir():
  52. root_tree.add("[dim]🐍 __init__.py[/dim]")
  53. tree = root_tree
  54. for sub_path in module_paths[1:]:
  55. sub_name = (
  56. f"🐍 {sub_path.name}" if sub_path.is_file() else f"📁 {sub_path.name}"
  57. )
  58. tree = tree.add(sub_name)
  59. if sub_path.is_dir():
  60. tree.add("[dim]🐍 __init__.py[/dim]")
  61. return root_tree
  62. def _run(
  63. path: Union[Path, None] = None,
  64. *,
  65. host: str = "127.0.0.1",
  66. port: int = 8000,
  67. reload: bool = True,
  68. workers: Union[int, None] = None,
  69. root_path: str = "",
  70. command: str,
  71. app: Union[str, None] = None,
  72. proxy_headers: bool = False,
  73. ) -> None:
  74. with get_rich_toolkit() as toolkit:
  75. server_type = "development" if command == "dev" else "production"
  76. toolkit.print_title(f"Starting {server_type} server 🚀", tag="FastAPI")
  77. toolkit.print_line()
  78. toolkit.print(
  79. "Searching for package file structure from directories with [blue]__init__.py[/blue] files"
  80. )
  81. try:
  82. import_data = get_import_data(path=path, app_name=app)
  83. except FastAPICLIException as e:
  84. toolkit.print_line()
  85. toolkit.print(f"[error]{e}")
  86. raise typer.Exit(code=1) from None
  87. logger.debug(f"Importing from {import_data.module_data.extra_sys_path}")
  88. logger.debug(f"Importing module {import_data.module_data.module_import_str}")
  89. module_data = import_data.module_data
  90. import_string = import_data.import_string
  91. toolkit.print(f"Importing from {module_data.extra_sys_path}")
  92. toolkit.print_line()
  93. root_tree = _get_module_tree(module_data.module_paths)
  94. toolkit.print(root_tree, tag="module")
  95. toolkit.print_line()
  96. toolkit.print(
  97. "Importing the FastAPI app object from the module with the following code:",
  98. tag="code",
  99. )
  100. toolkit.print_line()
  101. toolkit.print(
  102. f"[underline]from [bold]{module_data.module_import_str}[/bold] import [bold]{import_data.app_name}[/bold]"
  103. )
  104. toolkit.print_line()
  105. toolkit.print(
  106. f"Using import string: [blue]{import_string}[/]",
  107. tag="app",
  108. )
  109. url = f"http://{host}:{port}"
  110. url_docs = f"{url}/docs"
  111. toolkit.print_line()
  112. toolkit.print(
  113. f"Server started at [link={url}]{url}[/]",
  114. f"Documentation at [link={url_docs}]{url_docs}[/]",
  115. tag="server",
  116. )
  117. if command == "dev":
  118. toolkit.print_line()
  119. toolkit.print(
  120. "Running in development mode, for production use: [bold]fastapi run[/]",
  121. tag="tip",
  122. )
  123. if not uvicorn:
  124. raise FastAPICLIException(
  125. "Could not import Uvicorn, try running 'pip install uvicorn'"
  126. ) from None
  127. toolkit.print_line()
  128. toolkit.print("Logs:")
  129. toolkit.print_line()
  130. uvicorn.run(
  131. app=import_string,
  132. host=host,
  133. port=port,
  134. reload=reload,
  135. workers=workers,
  136. root_path=root_path,
  137. proxy_headers=proxy_headers,
  138. log_config=get_uvicorn_log_config(),
  139. )
  140. @app.command()
  141. def dev(
  142. path: Annotated[
  143. Union[Path, None],
  144. typer.Argument(
  145. help="A path to a Python file or package directory (with [blue]__init__.py[/blue] files) containing a [bold]FastAPI[/bold] app. If not provided, a default set of paths will be tried."
  146. ),
  147. ] = None,
  148. *,
  149. host: Annotated[
  150. str,
  151. typer.Option(
  152. help="The host to serve on. For local development in localhost use [blue]127.0.0.1[/blue]. To enable public access, e.g. in a container, use all the IP addresses available with [blue]0.0.0.0[/blue]."
  153. ),
  154. ] = "127.0.0.1",
  155. port: Annotated[
  156. int,
  157. typer.Option(
  158. help="The port to serve on. You would normally have a termination proxy on top (another program) handling HTTPS on port [blue]443[/blue] and HTTP on port [blue]80[/blue], transferring the communication to your app."
  159. ),
  160. ] = 8000,
  161. reload: Annotated[
  162. bool,
  163. typer.Option(
  164. help="Enable auto-reload of the server when (code) files change. This is [bold]resource intensive[/bold], use it only during development."
  165. ),
  166. ] = True,
  167. root_path: Annotated[
  168. str,
  169. typer.Option(
  170. help="The root path is used to tell your app that it is being served to the outside world with some [bold]path prefix[/bold] set up in some termination proxy or similar."
  171. ),
  172. ] = "",
  173. app: Annotated[
  174. Union[str, None],
  175. typer.Option(
  176. help="The name of the variable that contains the [bold]FastAPI[/bold] app in the imported module or package. If not provided, it is detected automatically."
  177. ),
  178. ] = None,
  179. proxy_headers: Annotated[
  180. bool,
  181. typer.Option(
  182. help="Enable/Disable X-Forwarded-Proto, X-Forwarded-For, X-Forwarded-Port to populate remote address info."
  183. ),
  184. ] = True,
  185. ) -> Any:
  186. """
  187. Run a [bold]FastAPI[/bold] app in [yellow]development[/yellow] mode. 🧪
  188. This is equivalent to [bold]fastapi run[/bold] but with [bold]reload[/bold] enabled and listening on the [blue]127.0.0.1[/blue] address.
  189. It automatically detects the Python module or package that needs to be imported based on the file or directory path passed.
  190. If no path is passed, it tries with:
  191. - [blue]main.py[/blue]
  192. - [blue]app.py[/blue]
  193. - [blue]api.py[/blue]
  194. - [blue]app/main.py[/blue]
  195. - [blue]app/app.py[/blue]
  196. - [blue]app/api.py[/blue]
  197. It also detects the directory that needs to be added to the [bold]PYTHONPATH[/bold] to make the app importable and adds it.
  198. It detects the [bold]FastAPI[/bold] app object to use. By default it looks in the module or package for an object named:
  199. - [blue]app[/blue]
  200. - [blue]api[/blue]
  201. Otherwise, it uses the first [bold]FastAPI[/bold] app found in the imported module or package.
  202. """
  203. _run(
  204. path=path,
  205. host=host,
  206. port=port,
  207. reload=reload,
  208. root_path=root_path,
  209. app=app,
  210. command="dev",
  211. proxy_headers=proxy_headers,
  212. )
  213. @app.command()
  214. def run(
  215. path: Annotated[
  216. Union[Path, None],
  217. typer.Argument(
  218. help="A path to a Python file or package directory (with [blue]__init__.py[/blue] files) containing a [bold]FastAPI[/bold] app. If not provided, a default set of paths will be tried."
  219. ),
  220. ] = None,
  221. *,
  222. host: Annotated[
  223. str,
  224. typer.Option(
  225. help="The host to serve on. For local development in localhost use [blue]127.0.0.1[/blue]. To enable public access, e.g. in a container, use all the IP addresses available with [blue]0.0.0.0[/blue]."
  226. ),
  227. ] = "0.0.0.0",
  228. port: Annotated[
  229. int,
  230. typer.Option(
  231. help="The port to serve on. You would normally have a termination proxy on top (another program) handling HTTPS on port [blue]443[/blue] and HTTP on port [blue]80[/blue], transferring the communication to your app."
  232. ),
  233. ] = 8000,
  234. reload: Annotated[
  235. bool,
  236. typer.Option(
  237. help="Enable auto-reload of the server when (code) files change. This is [bold]resource intensive[/bold], use it only during development."
  238. ),
  239. ] = False,
  240. workers: Annotated[
  241. Union[int, None],
  242. typer.Option(
  243. help="Use multiple worker processes. Mutually exclusive with the --reload flag."
  244. ),
  245. ] = None,
  246. root_path: Annotated[
  247. str,
  248. typer.Option(
  249. help="The root path is used to tell your app that it is being served to the outside world with some [bold]path prefix[/bold] set up in some termination proxy or similar."
  250. ),
  251. ] = "",
  252. app: Annotated[
  253. Union[str, None],
  254. typer.Option(
  255. help="The name of the variable that contains the [bold]FastAPI[/bold] app in the imported module or package. If not provided, it is detected automatically."
  256. ),
  257. ] = None,
  258. proxy_headers: Annotated[
  259. bool,
  260. typer.Option(
  261. help="Enable/Disable X-Forwarded-Proto, X-Forwarded-For, X-Forwarded-Port to populate remote address info."
  262. ),
  263. ] = True,
  264. ) -> Any:
  265. """
  266. Run a [bold]FastAPI[/bold] app in [green]production[/green] mode. 🚀
  267. This is equivalent to [bold]fastapi dev[/bold] but with [bold]reload[/bold] disabled and listening on the [blue]0.0.0.0[/blue] address.
  268. It automatically detects the Python module or package that needs to be imported based on the file or directory path passed.
  269. If no path is passed, it tries with:
  270. - [blue]main.py[/blue]
  271. - [blue]app.py[/blue]
  272. - [blue]api.py[/blue]
  273. - [blue]app/main.py[/blue]
  274. - [blue]app/app.py[/blue]
  275. - [blue]app/api.py[/blue]
  276. It also detects the directory that needs to be added to the [bold]PYTHONPATH[/bold] to make the app importable and adds it.
  277. It detects the [bold]FastAPI[/bold] app object to use. By default it looks in the module or package for an object named:
  278. - [blue]app[/blue]
  279. - [blue]api[/blue]
  280. Otherwise, it uses the first [bold]FastAPI[/bold] app found in the imported module or package.
  281. """
  282. _run(
  283. path=path,
  284. host=host,
  285. port=port,
  286. reload=reload,
  287. workers=workers,
  288. root_path=root_path,
  289. app=app,
  290. command="run",
  291. proxy_headers=proxy_headers,
  292. )
  293. def main() -> None:
  294. app()