Compare commits

..
6 Commits
Author SHA1 Message Date
LeoVasanko d1e82b5955 Treat dict log_config without a version key as an overlay on uvicorn defaults.
A partial log_config (no "version" key) is deep-merged over uvicorn's
default config before our patching, so users pass only their
customizations, e.g. log_config={"loggers": {"myapp": {"level":
"DEBUG"}}}.  Previously such dicts crashed at startup: dictConfig
requires a version, and our root entry referenced a "default" handler
that might not exist; that reference is now only added when the handler
exists.  The stock default formatter is replaced only when untouched,
so an overlaid fmt survives.  Dicts with version and non-dict configs
behave as before.  Documented in the README logging section, with tests
under fastapi-vue/tests (each patched config validated through
dictConfig).
2026-09-16 03:57:44 +00:00
LeoVasanko 5730e5dd01 Document logging principles under the server section. 2026-09-16 02:52:46 +00:00
LeoVasanko 3a9c5d1674 Set root logger level by dev mode, drop kanta logging config.
The root logger entry patch_log_config adds now uses INFO in dev and
WARNING in production (Python's default), so third-party library INFO
noise stays silent in production while subloggers remain free to
define their own level overrides.  A user-supplied root level still
wins (setdefault).

staticfiles now logs via its own module logger instead of
uvicorn.error: the startup stats line shows in dev (root INFO) and is
hidden in production, and it no longer passes through the
uvicorn-quiet filter that silently ate it.

The kanta logger/handler/formatter block is removed: kanta configures
its own event loggers at import time as of its logging rework, and its
diagnostics follow the root logger like any other library.
2026-09-16 02:22:35 +00:00
LeoVasanko 22d9fe350b Migrate pre-1.6 DEVMODE to fastapi_vue.env with in-place patching, run uv sync after dependency changes. 2026-09-14 04:22:24 +00:00
LeoVasanko 42adf6120d Replace startupbox in code box with an actual screenshot. 2026-09-14 03:38:36 +00:00
LeoVasanko 5ab12187bd Add new screenshot of a simulated My App run. 2026-09-14 03:05:17 +00:00
11 changed files with 239 additions and 79 deletions
+2
View File
@@ -129,3 +129,5 @@ The installed application instead depends on the lightweight [fastapi_vue](https
This keeps the development tooling where it belongs while leaving the distributed application as a normal, self-contained Python package. This keeps the development tooling where it belongs while leaving the distributed application as a normal, self-contained Python package.
️ The version numbering between the runtime and setup packages is synchronized, and the setup script always bumps the version in `pyproject.toml` to ensure compatible updates. ️ The version numbering between the runtime and setup packages is synchronized, and the setup script always bumps the version in `pyproject.toml` to ensure compatible updates.
<img src="https://raw.githubusercontent.com/LeoVasanko/fastapi-vue-setup/main/docs/my-app.webp" alt="My App startup box and log items" width="500">
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

+8 -10
View File
@@ -73,21 +73,19 @@ A single `reload` argument replaces Uvicorn's separate reload arguments and may
A startup box with the app name, version and connect URL is printed before serving. Pass a `startup_box` template (`{name}`, `{version}`, `{listen}`, `{url}`, ...) to customize it, None to disable, or use `server.print_startup_box` on its own. A startup box with the app name, version and connect URL is printed before serving. Pass a `startup_box` template (`{name}`, `{version}`, `{listen}`, `{url}`, ...) to customize it, None to disable, or use `server.print_startup_box` on its own.
Printed by `server.run("my_app.app:app", listen=["localhost:3100"])`: <img src="https://raw.githubusercontent.com/LeoVasanko/fastapi-vue-setup/main/docs/my-app.webp" alt="My App startup box and log items" width="500">
```
╭──────────────────────────────────────────╮
│ My App 0.1.0 @ 127.0.0.1:3100 [::1]:3100 │
│ http://localhost:3100 │
╰──────────────────────────────────────────╯
```
Logging is integrated as well: removes noisy uvicorn logging, replacing it with prettified log formatting, a colored access log and tracebacks rendered by [tracerite](https://pypi.org/project/tracerite/). Note that HTTP responses also include tracerite formatting when `FastAPI(debug=True)` is used.
Other arguments are generally passed to `uvicorn.run`, although some like `log_config` receive our modifications. Other arguments are generally passed to `uvicorn.run`, although some like `log_config` receive our modifications.
> As a deployment option, environment `FORWARDED_ALLOW_IPS` controls `X-Forwarded` trusted IPs (default: `127.0.0.1,::1` works for typical setups). > As a deployment option, environment `FORWARDED_ALLOW_IPS` controls `X-Forwarded` trusted IPs (default: `127.0.0.1,::1` works for typical setups).
### Logging and exceptions
Pretty logging is configured automatically across the host process and all workers, at INFO in development and WARNING in production, with emoji level prefixes, colored access logs, and tracebacks rendered by [tracerite](https://pypi.org/project/tracerite/). With `FastAPI(debug=True)`, **Internal Server Error** responses use tracerite formatting as well.
Application code can simply use `logging.info()` through `logging.exception()`, or ordinary `logging.getLogger("myapp")` loggers, without setting up logging itself. Set any logger's level when part of the application should be quieter or more verbose, for example `log_config={"loggers": {"myapp": {"level": "DEBUG"}}}`, accepting additions and overrides using [Python's logging configuration schema](https://docs.python.org/3/library/logging.config.html#logging-config-dictschema).
### Environment (fastapi_vue.env) ### Environment (fastapi_vue.env)
We use environment variables to pass values between program components, from devserver script setting dev mode and telling backend and frontend URLs, to your CLI, which in turn runs the FastAPI app that may also need access to this information. The variables are prefixed by the current application name to avoid conflicts. The CLI entry point should set one like `os.environ["FASTAPI_VUE"] = "MY_APP"`, before using `server.run` We use environment variables to pass values between program components, from devserver script setting dev mode and telling backend and frontend URLs, to your CLI, which in turn runs the FastAPI app that may also need access to this information. The variables are prefixed by the current application name to avoid conflicts. The CLI entry point should set one like `os.environ["FASTAPI_VUE"] = "MY_APP"`, before using `server.run`
+30 -28
View File
@@ -20,7 +20,7 @@ from typing import TYPE_CHECKING, Literal
import tracerite import tracerite
from starlette.middleware.errors import ServerErrorMiddleware from starlette.middleware.errors import ServerErrorMiddleware
from starlette.responses import HTMLResponse, JSONResponse, PlainTextResponse, Response from starlette.responses import HTMLResponse, JSONResponse, PlainTextResponse, Response
from uvicorn.config import Config from uvicorn.config import LOGGING_CONFIG, Config
from uvicorn.lifespan.on import LifespanOn from uvicorn.lifespan.on import LifespanOn
if TYPE_CHECKING: if TYPE_CHECKING:
@@ -31,6 +31,7 @@ if TYPE_CHECKING:
from uvicorn.lifespan.on import LifespanSendMessage from uvicorn.lifespan.on import LifespanSendMessage
from .accesslog import AccessLogMiddleware from .accesslog import AccessLogMiddleware
from .environ import env
ANSI_ESCAPE_RE = re.compile(r"\x1b\[[0-9;]*m") ANSI_ESCAPE_RE = re.compile(r"\x1b\[[0-9;]*m")
@@ -298,13 +299,25 @@ def patch_server_error_middleware() -> None:
ServerErrorMiddleware.error_response = error_response # type: ignore[method-assign] ServerErrorMiddleware.error_response = error_response # type: ignore[method-assign]
def _merge_log_config(base: dict, overlay: dict) -> dict:
"""Deep-merge *overlay* onto *base*; dicts merge recursively, others replace."""
for key, value in overlay.items():
if isinstance(value, dict) and isinstance(base.get(key), dict):
_merge_log_config(base[key], value)
else:
base[key] = value
return base
def patch_log_config(log_config, *, access_log: bool = True): # noqa: ANN001, ANN201 def patch_log_config(log_config, *, access_log: bool = True): # noqa: ANN001, ANN201
"""Patch a uvicorn log_config dict for our logging, best-effort. """Patch a uvicorn log_config dict for our logging, best-effort.
Users presumably base their config on uvicorn's default dict, but any A dict without a ``version`` key is treated as a partial config: it is
shape is tolerated: pieces that do not fit the config's structure are merged over uvicorn's default dict, so only the customizations are
silently skipped. Non-dict configs (e.g. an ini file path) pass through needed (e.g. ``{"loggers": {"kanta": {"level": "DEBUG"}}}``). A dict
untouched. with ``version`` is a complete config used as-is; pieces that do not
fit its structure are silently skipped. Non-dict configs (e.g. an ini
file path) pass through untouched.
Always adds an unreferenced NullHandler whose Formatter instantiation Always adds an unreferenced NullHandler whose Formatter instantiation
loads tracerite in every process uvicorn applies the config in, filters loads tracerite in every process uvicorn applies the config in, filters
@@ -312,7 +325,8 @@ def patch_log_config(log_config, *, access_log: bool = True): # noqa: ANN001, A
routine INFO lines, an emoji-level-prefix Formatter in place of routine INFO lines, an emoji-level-prefix Formatter in place of
uvicorn's stock ``default`` formatter (a user-supplied one wins), a root uvicorn's stock ``default`` formatter (a user-supplied one wins), a root
logger entry so ``logging.info()`` et al. print through the default logger entry so ``logging.info()`` et al. print through the default
handler, and a no-prefix ``kanta`` logger entry (likewise). The handler when one exists, at INFO in dev and WARNING in production
(matching Python's default). The
``watchfiles.main`` logger is lifted to WARNING so its INFO "N changes ``watchfiles.main`` logger is lifted to WARNING so its INFO "N changes
detected" line is dropped while the WARNING "Reloading..." line (logged detected" line is dropped while the WARNING "Reloading..." line (logged
to ``uvicorn.error``) still shows; a user-supplied level wins. to ``uvicorn.error``) still shows; a user-supplied level wins.
@@ -325,6 +339,8 @@ def patch_log_config(log_config, *, access_log: bool = True): # noqa: ANN001, A
if not isinstance(log_config, dict): if not isinstance(log_config, dict):
return log_config return log_config
config = deepcopy(log_config) config = deepcopy(log_config)
if "version" not in config:
config = _merge_log_config(deepcopy(LOGGING_CONFIG), config)
with suppress(Exception): with suppress(Exception):
config["formatters"]["fastapi_vue"] = {"()": "fastapi_vue.logging.Formatter"} config["formatters"]["fastapi_vue"] = {"()": "fastapi_vue.logging.Formatter"}
@@ -346,7 +362,7 @@ def patch_log_config(log_config, *, access_log: bool = True): # noqa: ANN001, A
# default formatter; a user-supplied default formatter is left alone. # default formatter; a user-supplied default formatter is left alone.
with suppress(Exception): with suppress(Exception):
default = config["formatters"]["default"] default = config["formatters"]["default"]
if default.get("()") in (None, "uvicorn.logging.DefaultFormatter"): if default == LOGGING_CONFIG["formatters"]["default"]:
config["formatters"]["default"] = { config["formatters"]["default"] = {
"()": "fastapi_vue.logging.Formatter", "()": "fastapi_vue.logging.Formatter",
"fmt": "%(message)s", "fmt": "%(message)s",
@@ -355,12 +371,15 @@ def patch_log_config(log_config, *, access_log: bool = True): # noqa: ANN001, A
# uvicorn's default config leaves the root logger handlerless, eating # uvicorn's default config leaves the root logger handlerless, eating
# logging.info() et al.; route root through uvicorn's default handler. # logging.info() et al.; route root through uvicorn's default handler.
# Level is WARNING in production so third-party loggers stay quiet, as
# with Python's default; dev keeps INFO. Subloggers can override.
with suppress(Exception): with suppress(Exception):
root = config.setdefault("root", {}) root = config.setdefault("root", {})
root.setdefault("level", "INFO") root.setdefault("level", "INFO" if env.dev else "WARNING")
root_handlers = root.setdefault("handlers", []) if "default" in config.get("handlers", {}):
if "default" not in root_handlers: root_handlers = root.setdefault("handlers", [])
root_handlers.append("default") if "default" not in root_handlers:
root_handlers.append("default")
# watchfiles logs "N changes detected" to its own logger at INFO; only the # watchfiles logs "N changes detected" to its own logger at INFO; only the
# WARNING "Reloading..." line (uvicorn.error) should show. # WARNING "Reloading..." line (uvicorn.error) should show.
@@ -369,23 +388,6 @@ def patch_log_config(log_config, *, access_log: bool = True): # noqa: ANN001, A
"level", "WARNING" "level", "WARNING"
) )
# kanta-style output (diffs, colored headers) prints without prefixes,
# like our access log. A user-supplied "kanta" logger entry wins.
with suppress(Exception):
config["formatters"].setdefault("plain", {"fmt": "%(message)s"})
config["handlers"].setdefault(
"plain",
{
"class": "logging.StreamHandler",
"formatter": "plain",
"stream": "ext://sys.stderr",
},
)
config.setdefault("loggers", {}).setdefault(
"kanta",
{"handlers": ["plain"], "level": "INFO", "propagate": False},
)
if access_log: if access_log:
with suppress(Exception): with suppress(Exception):
config["formatters"]["access"] = { config["formatters"]["access"] = {
+1 -1
View File
@@ -21,7 +21,7 @@ from zstandard import ZstdCompressor
from .environ import env from .environ import env
logger = logging.getLogger("uvicorn.error") # Use FastAPI logging style logger = logging.getLogger(__name__)
__all__ = ["Frontend"] __all__ = ["Frontend"]
+1
View File
@@ -0,0 +1 @@
"""Tests for the fastapi_vue package."""
+60
View File
@@ -0,0 +1,60 @@
"""Tests for fastapi_vue.logging.patch_log_config overlay behavior."""
import logging.config
from fastapi_vue.logging import patch_log_config
def test_empty_dict_overlays_uvicorn_defaults() -> None:
"""An empty dict is a partial config: merged over uvicorn's defaults."""
config = patch_log_config({})
assert config["version"] == 1
assert config["disable_existing_loggers"] is False
assert config["root"]["handlers"] == ["default"]
assert "uvicorn" in config["loggers"]
logging.config.dictConfig(config) # must be a valid, complete config
def test_partial_logger_customization() -> None:
"""The documented use case: only the customization, no boilerplate."""
config = patch_log_config({"loggers": {"kanta": {"level": "DEBUG"}}})
assert config["loggers"]["kanta"] == {"level": "DEBUG"}
assert config["loggers"]["uvicorn"]["handlers"] == ["default"]
assert config["loggers"]["watchfiles.main"]["level"] == "WARNING"
logging.config.dictConfig(config)
assert logging.getLogger("kanta").level == logging.DEBUG
def test_overlay_root_level_wins() -> None:
"""User-supplied root level is kept; our handler wiring still applies."""
config = patch_log_config({"root": {"level": "ERROR"}})
assert config["root"]["level"] == "ERROR"
assert config["root"]["handlers"] == ["default"]
logging.config.dictConfig(config)
assert logging.getLogger().level == logging.ERROR
def test_overlay_formatter_customization_keeps_stock_siblings() -> None:
"""A user formatter replaces ours; the access formatter still works."""
config = patch_log_config({"formatters": {"default": {"fmt": "%(name)s %(message)s"}}})
assert config["formatters"]["default"] == {
"()": "uvicorn.logging.DefaultFormatter", # stock class, user's fmt
"fmt": "%(name)s %(message)s",
"use_colors": None,
}
assert "access" in config["formatters"]
logging.config.dictConfig(config)
def test_full_config_used_as_is() -> None:
"""A dict with version is complete: no uvicorn loggers appear."""
config = patch_log_config({"version": 1})
assert "uvicorn" not in config.get("loggers", {})
# No "default" handler exists, so root must not reference one.
assert "handlers" not in config["root"]
logging.config.dictConfig(config)
def test_non_dict_passes_through() -> None:
"""Non-dict configs (e.g. an ini file path) are returned untouched."""
assert patch_log_config("logging.ini") == "logging.ini"
+131 -34
View File
@@ -111,12 +111,14 @@ def ruff_format_content(
def uv_add_packages(packages: list[str], *, cwd: Path, group: str | None = None) -> None: def uv_add_packages(packages: list[str], *, cwd: Path, group: str | None = None) -> None:
"""Add packages using uv.""" """Add packages using uv.
cmd = ["uv", "add", "-q", "-U"]
Uses --frozen so only pyproject.toml is edited, without locking or
syncing - those happen in a single uv sync step after all changes.
"""
cmd = ["uv", "add", "-q", "--frozen"]
if group: if group:
cmd.extend(["--group", group]) cmd.extend(["--group", group])
else:
cmd.append("--no-sync")
cmd.extend(packages) cmd.extend(packages)
result = subprocess.run(cmd, cwd=cwd, check=False) # noqa: S603 result = subprocess.run(cmd, cwd=cwd, check=False) # noqa: S603
if result.returncode != 0: if result.returncode != 0:
@@ -161,7 +163,7 @@ NEW_BUILD_HOOK_PATH = "scripts/fastapi-vue/buildhook.py"
# Frontend instantiation block for patching existing apps # Frontend instantiation block for patching existing apps
FRONTEND_BLOCK = """ FRONTEND_BLOCK = """
# Vue Frontend static files # Vue Frontend static files
frontend = fastapi_vue.Frontend(Path(__file__).with_name("frontend-build")) frontend = Frontend(Path(__file__).with_name("frontend-build"))
""" """
# Lifespan block for patching apps that don't have one # Lifespan block for patching apps that don't have one
@@ -473,6 +475,74 @@ def _find_app_in_subpackage(subpkg_dir: Path) -> tuple[Path, str] | None:
return None return None
def _migrate_devmode_in_main(content: str) -> str | None:
"""Spot-patch the pre-1.6 DEVMODE mechanism to the FASTAPI_VUE env prefix.
Replaces `DEVMODE = os.getenv("PREFIX_DEV") == "1"` with
`os.environ["FASTAPI_VUE"] = "PREFIX"` and remaining DEVMODE references
with env.dev, ensuring env is imported from fastapi_vue.
Returns the patched content, or None if there was nothing to patch.
"""
match = re.search(
r"^DEVMODE\s*=\s*os\.getenv\(\s*[\"']([A-Za-z0-9_]+)_DEV[\"']\s*\)\s*==\s*[\"']1[\"']",
content,
re.MULTILINE,
)
if not match:
return None
content = (
content[: match.start()]
+ f'os.environ["FASTAPI_VUE"] = "{match.group(1)}"'
+ content[match.end() :]
)
# Replace every remaining standalone DEVMODE reference (as in app.py
# migration, string literals are an accepted risk)
content = re.sub(r"(?<![\w.])DEVMODE\b", "env.dev", content)
if not re.search(r"^from fastapi_vue import\b.*\benv\b", content, re.MULTILINE):
if re.search(r"^from fastapi_vue import ", content, re.MULTILINE):
content = re.sub(
r"^from fastapi_vue import ",
"from fastapi_vue import env, ",
content,
count=1,
flags=re.MULTILINE,
)
else:
insert_line = find_import_insertion_line(content)
lines = content.splitlines(keepends=True)
insert_idx = insert_line - 1
import_text = "from fastapi_vue import env\n"
if insert_idx >= len(lines):
content = content.rstrip("\n") + "\n" + import_text
else:
content = "".join(lines[:insert_idx]) + import_text + "".join(lines[insert_idx:])
return content
def _patch_main_devmode(path: Path, *, dry: bool) -> str | None:
"""Apply _migrate_devmode_in_main to a main module in place, if needed.
Done in place even without the auto-upgrade marker: the marker guards
full-file overwrites, while leaving this change to a .new.py merge would
silently break dev mode for every customized pre-1.6 main.
Returns the migrated content if the module was (or would be) patched,
None if there was nothing to patch.
"""
content = path.read_text("UTF-8")
migrated = _migrate_devmode_in_main(content)
if migrated is None:
return None
migrated = ruff_format_content(migrated, path, mode="isort")
if dry:
print(f"✅ Would patch {path} (DEVMODE → FASTAPI_VUE)")
return migrated
path.write_text(migrated, "UTF-8", newline="\n")
print(f"✅ Patched {path} (DEVMODE → FASTAPI_VUE)")
return migrated
def _add_env_prefix_to_main(content: str) -> str: def _add_env_prefix_to_main(content: str) -> str:
"""Add FASTAPI_VUE environment prefix setup to an existing main module.""" """Add FASTAPI_VUE environment prefix setup to an existing main module."""
lines = content.splitlines() lines = content.splitlines()
@@ -600,10 +670,9 @@ def render_template(template: str, **kwargs: str) -> str:
def needs_app_migration(project_dir: Path) -> bool: def needs_app_migration(project_dir: Path) -> bool:
"""Check if the project was set up with fastapi-vue older than 1.6. """Check if the project was set up with fastapi-vue older than 1.6.
Those versions patched app.py with `from fastapi_vue import Frontend` and Those versions patched app.py with a DEVMODE import from the main module;
a DEVMODE import from the main module; 1.6+ uses fastapi_vue.Frontend and 1.6+ uses env.dev from fastapi_vue instead. Must be called before the
fastapi_vue.env. Must be called before the dependency step rewrites the dependency step rewrites the fastapi-vue requirement in pyproject.toml.
fastapi-vue requirement in pyproject.toml.
""" """
pyproject = project_dir / "pyproject.toml" pyproject = project_dir / "pyproject.toml"
if not pyproject.exists(): if not pyproject.exists():
@@ -624,8 +693,8 @@ def patch_app_file(
Inserts imports at top (ruff will sort them), route at bottom, Inserts imports at top (ruff will sort them), route at bottom,
and tries to patch lifespan with frontend.load(). With migrate=True, and tries to patch lifespan with frontend.load(). With migrate=True,
pre-1.6 patching (plain Frontend, DEVMODE import) is first rewritten pre-1.6 patching (DEVMODE import from the main module) is first
to the current format. rewritten to the current format (env.dev).
Returns True if patched, False if already patched or failed. Returns True if patched, False if already patched or failed.
""" """
@@ -636,17 +705,18 @@ def patch_app_file(
original_content = path.read_text("UTF-8") original_content = path.read_text("UTF-8")
content = original_content content = original_content
# Migrate pre-1.6 patching to the current format: Frontend via the # Migrate pre-1.6 patching to the current format: DEVMODE via
# fastapi_vue module, DEVMODE via fastapi_vue.env # fastapi_vue.env (the Frontend import stays as-is)
if migrate: if migrate:
if "from fastapi_vue import Frontend\n" in content:
content = content.replace("from fastapi_vue import Frontend\n", "")
content = re.sub(r"(?<![\w.])Frontend\(", "fastapi_vue.Frontend(", content)
old_import = f"from {main_module_path} import DEVMODE" old_import = f"from {main_module_path} import DEVMODE"
if old_import in content: if old_import in content:
has_plain_import = re.search(r"^import fastapi_vue$", content, re.MULTILINE) # The import sort at the end merges this with any existing
content = content.replace(old_import, "" if has_plain_import else "import fastapi_vue") # `from fastapi_vue import Frontend` line
content = content.replace("debug=DEVMODE", "debug=fastapi_vue.env.dev") content = content.replace(old_import, "from fastapi_vue import env")
# Replace every remaining standalone DEVMODE reference (not just
# the debug= parameter); it may also appear inside string literals,
# but that's an accepted risk over AST rewriting
content = re.sub(r"(?<![\w.])DEVMODE\b", "env.dev", content)
# Check what's already patched; plain "Frontend(" so user modifications # Check what's already patched; plain "Frontend(" so user modifications
# of the integration (renames, different call shape) still count # of the integration (renames, different call shape) still count
@@ -662,12 +732,14 @@ def patch_app_file(
route_line = f'frontend.route({app_var}, "/")' route_line = f'frontend.route({app_var}, "/")'
# Add missing imports (using AST to find correct insertion point); # Add missing imports (using AST to find correct insertion point);
# every patch path uses fastapi_vue.*, so always ensure the plain import # the import sort at the end merges duplicate from-imports
imports = [] imports = []
if not has_frontend: if not has_frontend:
imports.append("from pathlib import Path") imports.append("from pathlib import Path")
if not re.search(r"^import fastapi_vue$", content, re.MULTILINE): if not has_frontend or not re.search(
imports.append("import fastapi_vue") r"^from fastapi_vue import\b.*\benv\b", content, re.MULTILINE
):
imports.append("from fastapi_vue import Frontend, env")
if imports: if imports:
insert_line = find_import_insertion_line(content) insert_line = find_import_insertion_line(content)
lines = content.splitlines(keepends=True) lines = content.splitlines(keepends=True)
@@ -702,14 +774,14 @@ def patch_app_file(
lines.append(route_line) lines.append(route_line)
content = "\n".join(lines) content = "\n".join(lines)
# Try to patch FastAPI() call with debug=fastapi_vue.env.dev if no debug arg exists # Try to patch FastAPI() call with debug=env.dev if no debug arg exists
if not has_debug_arg: if not has_debug_arg:
fastapi_pattern = r"(\w+\s*=\s*FastAPI\s*\()([^)]*)\)" fastapi_pattern = r"(\w+\s*=\s*FastAPI\s*\()([^)]*)\)"
for match in re.finditer(fastapi_pattern, content, re.DOTALL): for match in re.finditer(fastapi_pattern, content, re.DOTALL):
args = match.group(2) args = match.group(2)
if "debug" not in args: if "debug" not in args:
# Add debug=fastapi_vue.env.dev as last argument # Add debug=env.dev as last argument
new_args = (f"{args}, " if args.strip() else "") + "debug=fastapi_vue.env.dev" new_args = (f"{args}, " if args.strip() else "") + "debug=env.dev"
content = ( content = (
content[: match.start()] content[: match.start()]
+ match.group(1) + match.group(1)
@@ -1008,6 +1080,11 @@ def _upgrade_old_vite_plugin(path: Path, module_name: str, *, dry: bool = False)
_new_files_written: list[tuple[Path, Path]] = [] _new_files_written: list[tuple[Path, Path]] = []
def _strip_upgrade_marker(content: str) -> str:
"""Remove the auto-upgrade marker line, for content comparison."""
return "\n".join(line for line in content.splitlines() if UPGRADE_MARKER not in line)
def write_file( def write_file(
path: Path, path: Path,
content: str, content: str,
@@ -1531,14 +1608,26 @@ def cmd_setup(args: argparse.Namespace) -> int:
main_content = render_template(template, **tpl_vars) main_content = render_template(template, **tpl_vars)
if main_file.exists(): if main_file.exists():
# File exists: update if it has the auto-upgrade marker, otherwise use fallback # Spot-patch the pre-1.6 DEVMODE mechanism in place first - the
write_file( # auto-upgrade marker guards full-file overwrites, but leaving this
main_file, # change to a .new.py merge would silently break dev mode
main_content, migrated = _patch_main_devmode(main_file, dry=dry)
overwrite=True, existing = migrated if migrated is not None else main_file.read_text("UTF-8")
dry=dry, # Update if it has the auto-upgrade marker, otherwise use fallback -
fallback_path=main_fallback, # unless the markerless file is otherwise up to date (e.g. the
) # DEVMODE spot-patch was the only change), then no fallback is needed
if UPGRADE_MARKER not in existing and _strip_upgrade_marker(
existing
) == _strip_upgrade_marker(ruff_format_content(main_content, main_file)):
print(f"✔️ {main_file} (already up to date)")
else:
write_file(
main_file,
main_content,
overwrite=True,
dry=dry,
fallback_path=main_fallback,
)
elif not existing_cli_module: elif not existing_cli_module:
# No file and no existing entrypoint: create new __main__.py # No file and no existing entrypoint: create new __main__.py
write_file( write_file(
@@ -1558,7 +1647,8 @@ def cmd_setup(args: argparse.Namespace) -> int:
executable=False, executable=False,
) )
if main.exists(): if main.exists():
content = main.read_text("UTF-8") migrated = _patch_main_devmode(main, dry=dry)
content = migrated if migrated is not None else main.read_text("UTF-8")
if "FASTAPI_VUE" not in content: if "FASTAPI_VUE" not in content:
new_content = _add_env_prefix_to_main(content) new_content = _add_env_prefix_to_main(content)
new_file = main.with_suffix(".new.py") new_file = main.with_suffix(".new.py")
@@ -1651,9 +1741,16 @@ def cmd_setup(args: argparse.Namespace) -> int:
fastapi_vue_req = f"fastapi-vue~={mmp[1]}.{mmp[2]}.{mmp[3]}" if mmp else "fastapi-vue" fastapi_vue_req = f"fastapi-vue~={mmp[1]}.{mmp[2]}.{mmp[3]}" if mmp else "fastapi-vue"
if dry: if dry:
print(f"📦 Would add: fastapi[standard], {fastapi_vue_req}") print(f"📦 Would add: fastapi[standard], {fastapi_vue_req}")
print("📦 Would run: uv sync")
else: else:
print("📦 Dependencies") print("📦 Dependencies")
uv_add_packages(["fastapi[standard]", fastapi_vue_req], cwd=project_dir) uv_add_packages(["fastapi[standard]", fastapi_vue_req], cwd=project_dir)
# uv add runs with --frozen, so lock and sync the environment once
# everything is in place; attached to the terminal so the user sees
# the updates, and non-fatal - setup is complete either way
result = subprocess.run(["uv", "sync"], cwd=project_dir, check=False) # noqa: S607
if result.returncode != 0:
print("⚠️ uv sync failed - run it manually to update the environment")
print() print()
print_boxed("Setup complete!") print_boxed("Setup complete!")
+1
View File
@@ -49,3 +49,4 @@ ignore = ["CPY", "D203", "D213", "COM812", "PLR2004"]
"template/**" = ["F821"] # Undefined names are template placeholders "template/**" = ["F821"] # Undefined names are template placeholders
"template/scripts/devserver.py" = ["N806"] # MODULE_NAME is a template variable "template/scripts/devserver.py" = ["N806"] # MODULE_NAME is a template variable
"fastapi_vue_setup.py" = ["PLR", "C901", "T201", "RUF001"] "fastapi_vue_setup.py" = ["PLR", "C901", "T201", "RUF001"]
"**/tests/**" = ["S101"] # Asserts are the point of tests
+2 -3
View File
@@ -5,8 +5,7 @@ import argparse
import os import os
from pathlib import Path from pathlib import Path
import fastapi_vue from fastapi_vue import env, server
from fastapi_vue import server
DEFAULT_PORT = TEMPLATE_DEFAULT_PORT DEFAULT_PORT = TEMPLATE_DEFAULT_PORT
os.environ["FASTAPI_VUE"] = "ENVPREFIX" os.environ["FASTAPI_VUE"] = "ENVPREFIX"
@@ -27,7 +26,7 @@ def main() -> None:
listen=args.listen, listen=args.listen,
default_port=DEFAULT_PORT, default_port=DEFAULT_PORT,
server_header=False, server_header=False,
reload=Path(__file__).parent if fastapi_vue.env.dev else False, reload=Path(__file__).parent if env.dev else False,
) )
+3 -3
View File
@@ -4,11 +4,11 @@ from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from pathlib import Path from pathlib import Path
import fastapi_vue
from fastapi import FastAPI from fastapi import FastAPI
from fastapi_vue import Frontend, env
# Vue Frontend static files # Vue Frontend static files
frontend = fastapi_vue.Frontend(Path(__file__).with_name("frontend-build")) frontend = Frontend(Path(__file__).with_name("frontend-build"))
@asynccontextmanager @asynccontextmanager
@@ -18,7 +18,7 @@ async def lifespan(_app: FastAPI) -> AsyncGenerator:
yield yield
app = FastAPI(title="PROJECT_TITLE", debug=fastapi_vue.env.dev, lifespan=lifespan) app = FastAPI(title="PROJECT_TITLE", debug=env.dev, lifespan=lifespan)
# Add API routes here... # Add API routes here...