-
-
Notifications
You must be signed in to change notification settings - Fork 67
✨ Add support for reading configuration from pyproject.toml
#236
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
patrick91
wants to merge
3
commits into
main
Choose a base branch
from
10-17-_add_support_for_reading_configuration_from_pyproject.toml
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| import logging | ||
| from pathlib import Path | ||
| from typing import Any, Dict, Optional | ||
|
|
||
| from pydantic import BaseModel | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class FastAPIConfig(BaseModel): | ||
| entrypoint: Optional[str] = None | ||
| host: str = "127.0.0.1" | ||
| port: int = 8000 | ||
|
|
||
| @classmethod | ||
| def _read_pyproject_toml(cls) -> Dict[str, Any]: | ||
| """Read FastAPI configuration from pyproject.toml in current directory.""" | ||
| pyproject_path = Path.cwd() / "pyproject.toml" | ||
|
|
||
| if not pyproject_path.exists(): | ||
| return {} | ||
|
|
||
| try: | ||
| import tomllib # type: ignore[import-not-found, unused-ignore] | ||
| except ImportError: | ||
| try: | ||
| import tomli as tomllib # type: ignore[no-redef, import-not-found, unused-ignore] | ||
| except ImportError: # pragma: no cover | ||
| logger.debug("tomli not available, skipping pyproject.toml") | ||
| return {} | ||
|
|
||
| with open(pyproject_path, "rb") as f: | ||
| data = tomllib.load(f) | ||
|
|
||
| return data.get("tool", {}).get("fastapi", {}) # type: ignore | ||
|
|
||
| @classmethod | ||
| def resolve( | ||
| cls, | ||
| host: Optional[str] = None, | ||
| port: Optional[int] = None, | ||
| entrypoint: Optional[str] = None, | ||
| ) -> "FastAPIConfig": | ||
| config = cls._read_pyproject_toml() | ||
|
|
||
| if host is not None: | ||
| config["host"] = host | ||
| if port is not None: | ||
| config["port"] = port | ||
| if entrypoint is not None: | ||
| config["entrypoint"] = entrypoint | ||
|
|
||
| return FastAPIConfig.model_validate(config) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| from fastapi import FastAPI | ||
|
|
||
| app = FastAPI() | ||
|
|
||
|
|
||
| @app.get("/") | ||
| def read_root(): | ||
| return {"Hello": "World"} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| from fastapi import FastAPI | ||
|
|
||
| app = FastAPI() | ||
|
|
||
|
|
||
| @app.get("/") | ||
| def read_root(): | ||
| return {"Hello": "World"} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| [tool.fastapi] | ||
| entrypoint = "my_module:app" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| from pathlib import Path | ||
| from unittest.mock import patch | ||
|
|
||
| import uvicorn | ||
| from typer.testing import CliRunner | ||
|
|
||
| from fastapi_cli.cli import app | ||
| from tests.utils import changing_dir | ||
|
|
||
| runner = CliRunner() | ||
|
|
||
| assets_path = Path(__file__).parent / "assets" | ||
|
|
||
|
|
||
| def test_dev_with_pyproject_app_config_uses() -> None: | ||
| with changing_dir(assets_path / "pyproject_config"), patch.object( | ||
| uvicorn, "run" | ||
| ) as mock_run: | ||
| result = runner.invoke(app, ["dev"]) | ||
| assert result.exit_code == 0, result.output | ||
|
|
||
| assert mock_run.call_args.kwargs["app"] == "my_module:app" | ||
| assert mock_run.call_args.kwargs["host"] == "127.0.0.1" | ||
| assert mock_run.call_args.kwargs["port"] == 8000 | ||
| assert mock_run.call_args.kwargs["reload"] is True | ||
|
|
||
| assert "Using import string: my_module:app" in result.output | ||
|
|
||
|
|
||
| def test_run_with_pyproject_app_config() -> None: | ||
| with changing_dir(assets_path / "pyproject_config"), patch.object( | ||
| uvicorn, "run" | ||
| ) as mock_run: | ||
| result = runner.invoke(app, ["run"]) | ||
| assert result.exit_code == 0, result.output | ||
|
|
||
| assert mock_run.call_args.kwargs["app"] == "my_module:app" | ||
| assert mock_run.call_args.kwargs["host"] == "0.0.0.0" | ||
| assert mock_run.call_args.kwargs["port"] == 8000 | ||
| assert mock_run.call_args.kwargs["reload"] is False | ||
|
|
||
| assert "Using import string: my_module:app" in result.output | ||
|
|
||
|
|
||
| def test_cli_arg_overrides_pyproject_config() -> None: | ||
| with changing_dir(assets_path / "pyproject_config"), patch.object( | ||
| uvicorn, "run" | ||
| ) as mock_run: | ||
| result = runner.invoke(app, ["dev", "another_module.py"]) | ||
|
|
||
| assert result.exit_code == 0, result.output | ||
|
|
||
| assert mock_run.call_args.kwargs["app"] == "another_module:app" | ||
|
|
||
|
|
||
| def test_pyproject_app_config_invalid_format() -> None: | ||
| test_dir = assets_path / "pyproject_invalid_config" | ||
| test_dir.mkdir(exist_ok=True) | ||
|
|
||
| pyproject_file = test_dir / "pyproject.toml" | ||
| pyproject_file.write_text(""" | ||
| [tool.fastapi] | ||
| entrypoint = "invalid_format_without_colon" | ||
| """) | ||
|
|
||
| try: | ||
| with changing_dir(test_dir): | ||
| result = runner.invoke(app, ["dev"]) | ||
| assert result.exit_code == 1 | ||
| assert ( | ||
| "Import string must be in the format module.submodule:app_name" | ||
| in result.output | ||
| ) | ||
| finally: | ||
| pyproject_file.unlink() | ||
| test_dir.rmdir() | ||
|
|
||
|
|
||
| def test_pyproject_validation_error() -> None: | ||
| test_dir = assets_path / "pyproject_validation_error" | ||
| test_dir.mkdir(exist_ok=True) | ||
|
|
||
| pyproject_file = test_dir / "pyproject.toml" | ||
| pyproject_file.write_text(""" | ||
| [tool.fastapi] | ||
| entrypoint = 123 | ||
| """) | ||
|
|
||
| try: | ||
| with changing_dir(test_dir): | ||
| result = runner.invoke(app, ["dev"]) | ||
| assert result.exit_code == 1 | ||
| assert "Invalid configuration in pyproject.toml:" in result.output | ||
| assert "entrypoint" in result.output.lower() | ||
| finally: | ||
| pyproject_file.unlink() | ||
| test_dir.rmdir() |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It seems these
hostandportend up coming from the default values in the function definition, so they are never read frompyproject.toml😅I'm also wondering if we should add the host and port to the config. 🤔
With
fastapi devit defaults to localhost (127.0.0.1), withfastapi runit defaults to all hosts (0.0.0.0). Setting thehostin the config would end up taking precedence over the defaults, which could be counterintuitive, e.g. someone tries to run it somewhere in prod and because they had an override in the file, it no longer listens to all the hosts.I think I would suggest removing
hostfrompyproject.toml.About
port, maybe it would make sense to allow changing it, in particular if they have multiple apps and want to run them all at the same time, but we don't support that yet in this file config. But maybe it's worth keeping it.