Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5d1ba2f58c | ||
|
|
cf2957ab8d | ||
|
|
fbfd2ba1bb | ||
|
|
ff33df0ebc | ||
|
|
dec5191157 | ||
|
|
baab37ae2d | ||
|
|
ab2d721723 | ||
|
|
2d7e119161 | ||
|
|
d4f835428b | ||
|
|
1a22ec9dce |
@@ -1,96 +1,131 @@
|
||||
# fastapi-vue-setup
|
||||

|
||||
|
||||
Create or patch a FastAPI + Vue project with an integrated dev/build workflow.
|
||||
# FastAPI-Vue Full Stack Setup
|
||||
|
||||
- Development: one command runs Vite + FastAPI (reloads)
|
||||
- Production: `uv build` bakes the built Vue assets into the Python package (no Node/JS runtime needed to *run* the installed package)
|
||||
Build and develop **FastAPI + Vue** as a single project, while keeping production purely Python — **JavaScript tooling is only needed during development!**
|
||||
|
||||
Unlike a template repository or a tutorial, the setup adapts to the application you already have and can keep that integration up to date as the stack evolves. It also fills in the practical gaps around FastAPI itself, providing a production-ready application runtime with a CLI command to start the server with integrated pretty logging and tracebacks — giving your project a running start.
|
||||
|
||||
Start a new project with your preferred setup, integrate an existing FastAPI or Vue codebase, or upgrade an already integrated project to the latest simply by running the script.
|
||||
|
||||
## Quick start
|
||||
|
||||
Install [UV](https://docs.astral.sh/uv/) and any JS runtime (node, deno, or bun).
|
||||
|
||||
This README uses `my-app` as the example project name:
|
||||
|
||||
- project directory: `my-app/`
|
||||
- Python module: `my_app`
|
||||
- env prefix: `MY_APP`
|
||||
- CLI command: `my-app`
|
||||
|
||||
Create a new project in `./my-app`:
|
||||
|
||||
```sh
|
||||
Install [UV](https://docs.astral.sh/uv/getting-started/installation/) and Node ([nvm](https://github.com/nvm-sh/nvm#installing-and-updating)), and create your project:
|
||||
```
|
||||
uvx fastapi-vue-setup my-app
|
||||
```
|
||||
|
||||
Once in your source tree, you will typically use `.` for the path. If there is an existing project, `fastapi-vue-setup` will do its best to find and patch a backend module and create or patch a Vue project in `frontend/`. The integration can be upgraded by running a new version of `fastapi-vue-setup` on it, preserving earlier default ports and user customizations.
|
||||
Inside the new project, start the development server with live reloads and debug aids:
|
||||
```sh
|
||||
uv run scripts/devserver.py
|
||||
```
|
||||
|
||||
## In your project
|
||||
Or build a release package, and run anywhere:
|
||||
```sh
|
||||
uv build # a dist Python package
|
||||
uvx --with dist/my_app-0.1.0.tar.gz my-app --help
|
||||
```
|
||||
|
||||
ℹ️ Everything below is meant to be run within your project source tree.
|
||||
Or install as a proper executable:
|
||||
```sh
|
||||
uv tool install dist/my_app-0.1.0.tar.gz
|
||||
my-app --help
|
||||
```
|
||||
|
||||
The setup creates a CLI entry for your package, so that it becomes a command to run, not a Python module nor `fastapi myapp...`. The CLI main can be customized, although --listen should be kept for devserver compatibility.
|
||||
<img src="https://raw.githubusercontent.com/LeoVasanko/fastapi-vue-setup/main/docs/hello.webp" alt='"You did it" with Vue-FastAPI connection.' width="500">
|
||||
|
||||
You can choose the JS runtime with environment `JS_RUNTIME` (e.g. `node`, `deno`, `bun`, or path to one). This is used by the build and the devserver scripts. By default any available runtime on the system is chosen.
|
||||
## Working in your project
|
||||
|
||||
### Setup and upgrades
|
||||
|
||||
The setup command handles new projects, existing FastAPI or Vue projects, and projects previously configured by an older version. Use a project directory to create or migrate it, or `.` when already inside the source tree:
|
||||
|
||||
```sh
|
||||
uvx fastapi-vue-setup [project-dir] [options]
|
||||
```
|
||||
|
||||
| Option | Purpose |
|
||||
| -------------------------- | ------------------------------------------------------------------------------------------------------------ |
|
||||
| `--module-name NAME` | Override the Python module name, normally detected automatically |
|
||||
| `--ports BACKEND,VITE,DEV` | Set the production backend, development frontend and development backend ports; defaults to `3100,3100,3200` |
|
||||
| `--health PATH` | Endpoint used to wait for the development backend to become ready; use `--health=""` to disable the check |
|
||||
| `--dry`, `--dry-run` | Preview the changes without modifying the project |
|
||||
| `--version` | Print the setup version |
|
||||
| `-- ARGS` | Pass the remaining arguments to `create-vue` when a frontend needs to be created non-interactively |
|
||||
|
||||
Existing projects are inspected rather than replaced: the Python module, FastAPI application, CLI entry point and Vue project are reused where found, with missing pieces created as needed. Running a newer setup version on the project upgrades the generated integration while retaining configured ports and health checks unless explicitly overridden.
|
||||
|
||||
ℹ️ Generated files marked `auto-upgrade@fastapi-vue-setup` may be refreshed automatically on later runs. Remove that marker when taking ownership of a generated file; where an updated version is still useful, the setup writes a `.new.py` file for manual merging instead of overwriting your changes. Internal files under `scripts/fastapi-vue/` belong to the setup itself and are updated automatically.
|
||||
|
||||
### Main CLI (my-app)
|
||||
|
||||
The setup gives your application its own CLI command. This becomes the normal way to start it, rather than invoking via FastAPI CLI or by other means, except perhaps via `uv run` or `uvx` to run the latest version directly and avoid installation completely.
|
||||
|
||||
The generated `__main__.py` is yours to customize. Keep its `--listen` option if you want it to remain compatible with the development server that also passes arguments to your CLI entry point.
|
||||
|
||||
### Development server (Vite + FastAPI)
|
||||
|
||||
```sh
|
||||
uv run scripts/devserver.py [args]
|
||||
scripts/devserver.py [args]
|
||||
```
|
||||
|
||||
ℹ️ Arguments are forwarded to the main CLI, except that `--listen` controls where Vite listens, and `--backend` is passed to main CLI as `--listen`.
|
||||
ℹ️ Windows users have to use `uv run scripts/devserver.py`, while Linux and Mac users can just run the script directly.
|
||||
|
||||
This runs the Vite development server and FastAPI together, with reloads on both sides and the environment configured so they can communicate directly. Vite serves the Vue app and proxies specific paths to the FastAPI backend. The paths default to `/api/` only, and can be configured in your `vite.config.js` (or `vite.config.ts` if you chose TypeScript). In dev mode the browser only connects via Vite, and trying to load frontend assets from the backend is blocked.
|
||||
|
||||
- `--listen` set Vite listening port
|
||||
- `--backend` set FastAPI port (forwarded as `--listen`)
|
||||
- `--help` see help; any other arguments are passed directly to your CLI
|
||||
|
||||
JavaScript tooling is used only from the source tree, by the devserver and build commands. An available runtime is selected automatically; set `JS_RUNTIME` to `node`, `deno`, `bun`, or an executable path to choose one explicitly.
|
||||
|
||||
### Production
|
||||
|
||||
Build the Python package (this compiles the Vue frontend) and run the production server:
|
||||
Building the Python package also builds the Vue frontend, ensuring the source repository has a fresh build. If you wish to run production mode in your source repo, with a fresh build:
|
||||
|
||||
```sh
|
||||
```
|
||||
uv build && uv run my-app [args]
|
||||
```
|
||||
|
||||
Once happy with it, publish the package
|
||||
Publishing alike follows `uv build` and involves either copying the `dist/*.tar.gz` archive to where you need it, or `uv publish` to make it a public release that can be run directly by `uvx my-app`.
|
||||
|
||||
```sh
|
||||
uv build && uv publish
|
||||
```
|
||||
ℹ️ Other Python build and installation methods like `pip install` work equally well, we just prefer using UV.
|
||||
|
||||
Afterwards, you can easily run it anywhere, no JS runtimes required:
|
||||
## Project Layout
|
||||
|
||||
```sh
|
||||
uvx my-app [args]
|
||||
```
|
||||
|
||||
ℹ️ Instead of `uvx` you may consider `uv tool install`, oldskool `pip install` or whatever best suits you.
|
||||
|
||||
### Vite plugin
|
||||
|
||||
The generated Vite plugin lives in `frontend/vite-plugin-fastapi.js` and defaults to proxying `/api`.
|
||||
|
||||
It reads `MY_APP_BACKEND_URL` to know where to proxy; if unset it falls back to your configured default backend port.
|
||||
|
||||
## Project layout (typical)
|
||||
A newly created project typically looks like this:
|
||||
|
||||
```
|
||||
my-app/
|
||||
├── frontend/ # Vue app (Vite)
|
||||
├── frontend/ # Vue source (Node, Vite)
|
||||
│ ├── src/
|
||||
│ ├── vite-plugin-fastapi.js
|
||||
│ ├── vite-plugin-fastapi.js # Helper plugin
|
||||
│ ├── vite.config.js # Loads the plugin with app setup
|
||||
│ └── package.json
|
||||
├── my_app/ # Python package
|
||||
│ ├── __main__.py # CLI entrypoint
|
||||
│ ├── __init__.py
|
||||
│ ├── __main__.py # Application CLI
|
||||
│ ├── app.py # FastAPI app
|
||||
│ └── frontend-build/ # built assets (included in distributions)
|
||||
├── pyproject.toml
|
||||
└── scripts/
|
||||
├── devserver.py # Run Vite and FastAPI together in dev mode
|
||||
└── fastapi-vue/ # Dev utilities (only on the source tree)
|
||||
├── buildhook.py
|
||||
├── buildutil.py
|
||||
└── devutil.py
|
||||
│ └── frontend-build/ # Generated production frontend
|
||||
├── scripts/
|
||||
│ ├── devserver.py # Vite + FastAPI development server
|
||||
│ └── fastapi-vue/ # Generated build/dev support
|
||||
│ ├── buildhook.py
|
||||
│ ├── buildutil.py
|
||||
│ └── devutil.py
|
||||
└── pyproject.toml
|
||||
```
|
||||
|
||||
## The fastapi-vue runtime module
|
||||
Existing projects retain their own layout wherever possible; this is only the default structure.
|
||||
|
||||
The backend runs the FastAPI app and serves the frontend build using the companion package in [fastapi-vue/README.md](fastapi-vue/README.md). Your project will depend on Fastapi and this lightweight module.
|
||||
## Runtime and build tooling
|
||||
|
||||
ℹ️ Development functionality is in `scripts/fastapi-vue/` directly in your source tree, and is not to be confused with this runtime module. Only the runtime is installed with your package.
|
||||
There are deliberately two separate pieces to the integration.
|
||||
|
||||
The files under `scripts` written by the setup script belong to the source tree. They handle development and package building, and are not part of the Python package.
|
||||
|
||||
The installed application instead depends on the lightweight [fastapi_vue](https://pypi.org/project/fastapi-vue/) runtime module. It serves the built frontend and provides the server runner, logging and traceback integration used by the generated application.
|
||||
|
||||
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.
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 76 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 19 KiB |
+48
-17
@@ -1,13 +1,13 @@
|
||||
# fastapi-vue
|
||||
# FastAPI-Vue Runtime
|
||||
|
||||
Runtime helpers for FastAPI + Vite/Vue projects.
|
||||
Runtime utilities for making FastAPI apps standalone, with their own CLI entry point and facilities that make the FastAPI + Vue stack pleasant to use.
|
||||
|
||||
## Overview
|
||||
ℹ️ Use [fastapi-vue-setup](https://pypi.org/project/fastapi-vue-setup/) to set up your project. Everything below is configured automatically by it.
|
||||
|
||||
This package provides:
|
||||
## Main Components
|
||||
|
||||
- `fastapi_vue.Frontend`: serves built SPA assets (with SPA support, caching, and optional zstd)
|
||||
- `fastapi_vue.server.run`: a small Uvicorn runner with convenient `listen` endpoint parsing
|
||||
- **Frontend**: Serves static files with proper caching, compression and SPA support
|
||||
- **Server**: Runs the FastAPI app from your own CLI entry point with uvicorn facilities vastly augmented
|
||||
|
||||
## Quickstart
|
||||
|
||||
@@ -34,16 +34,16 @@ app = FastAPI(lifespan=lifespan)
|
||||
frontend.route(app, "/")
|
||||
```
|
||||
|
||||
## Frontend
|
||||
If SPA mode is disabled, we only route the paths that actually exist, leaving anything else to your own handlers that come after and may themselves wish to catch all that remains.
|
||||
|
||||
`Frontend` serves a directory with:
|
||||
## Frontend (fastapi_vue.Frontend)
|
||||
|
||||
- RAM caching, with zstd compression when smaller than original
|
||||
- Browser caching: ETag + Last-Modified, Immutable assets
|
||||
- Favicon mapping (serve PNG or other images there instead)
|
||||
- SPA routing (serve browsers index.html at all paths not otherwise handled)
|
||||
- Designed to serve at `/`, living together with your other routes
|
||||
- SPA routing: serves `index.html` for paths not otherwise handled
|
||||
- RAM caching with zstd compression
|
||||
- Browser caching with ETag, Last-Modified and immutable assets
|
||||
|
||||
Dev-mode behavior with `FastAPI(debug=True)`: requests error HTTP 409 with a message telling you to use the Vite dev server instead. Avoids accidentally using outdated `frontend-build` during development.
|
||||
With `FastAPI(debug=True)`, frontend requests return HTTP 409 with a message directing you to the Vite dev server. This prevents accidentally serving an outdated frontend build during development.
|
||||
|
||||
- `directory`: Path on local filesystem
|
||||
- `index`: Index file name (default: `index.html`)
|
||||
@@ -53,11 +53,13 @@ Dev-mode behavior with `FastAPI(debug=True)`: requests error HTTP 409 with a mes
|
||||
- `favicon`: Optional path or glob (e.g. `/assets/logo*.png`)
|
||||
- `zstdlevel`: Compression level (default: 18)
|
||||
|
||||
ℹ️ Even when your page has a meta tag giving favicon location, browsers still try loading `/favicon.ico` whenever looking at something else. We find it more convenient to simply serve the image where the browser expects it, with correct MIME type. This also allows having a default favicon for your application that can be easily overriden at the reverse proxy (Caddy, Nginx) to serve the company branding if needed in deployment.
|
||||
ℹ️ Browsers commonly request `/favicon.ico` even when another icon is specified in HTML. The favicon option lets you serve an SVG or PNG there instead. This also provides a convenient application default that a deployment reverse proxy such as Caddy or Nginx can override with company branding.
|
||||
|
||||
## Server runner
|
||||
## Server runner (fastapi_vue.server)
|
||||
|
||||
When you need more flexibility than `fastapi` CLI can provide (e.g. CLI arguments to your own program), you may use this convenience to run FastAPI app with Uvicorn startup on given `listen` endpoints. Runs in the same process if possible but delegates to `uvicorn.run()` for auto-reloads and multiple workers. This would typically be called from your CLI main, which can set its own env variables to pass information to the FastAPI instances that run (Python imports only work in same-process mode).
|
||||
When you need more flexibility than the `fastapi` CLI provides—for example, to support arguments in your own CLI—you can use the bundled server runner.
|
||||
|
||||
It starts the FastAPI app, running directly in the current process when possible and delegating to Uvicorn supervisors for reloads and multiple workers. The `server.run` is modeled after `uvicorn.run` that you would otherwise have to use to run FastAPI.
|
||||
|
||||
```python
|
||||
from fastapi_vue import server
|
||||
@@ -65,4 +67,33 @@ from fastapi_vue import server
|
||||
server.run("my_app.app:app", listen=["localhost:8000"])
|
||||
```
|
||||
|
||||
- As a deployment option, environment `FORWARDED_ALLOW_IPS` controls `X-Forwarded` trusted IPs (default: `127.0.0.1,::1`).
|
||||
Endpoints are plain strings: `host:port`, a bare port (localhost only), `:port` (all interfaces), or a unix socket path. Multiple endpoints can be served simultaneously. This also avoids Uvicorn's localhost limitation, where localhost may bind only to either 127.0.0.1 or ::1.
|
||||
|
||||
A single `reload` argument replaces Uvicorn's separate reload arguments and may directly specify paths to watch.
|
||||
|
||||
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"])`:
|
||||
|
||||
```
|
||||
╭──────────────────────────────────────────╮
|
||||
│ 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.
|
||||
|
||||
> As a deployment option, environment `FORWARDED_ALLOW_IPS` controls `X-Forwarded` trusted IPs (default: `127.0.0.1,::1` works for typical setups).
|
||||
|
||||
### 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`
|
||||
|
||||
The following properties read the environment and return `None` when variables haven't been set:
|
||||
|
||||
- `fastapi_vue.env.prefix` — the prefix itself
|
||||
- `fastapi_vue.env.dev` — running in development mode, from e.g. `MY_APP_DEV=1`
|
||||
- `fastapi_vue.env.vite_url`, `fastapi_vue.env.backend_url` — URLs set by the devserver
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""FastAPI Vue integration - serve Vue frontend from FastAPI."""
|
||||
|
||||
from .environ import env
|
||||
from .staticfiles import Frontend
|
||||
|
||||
__all__ = ["Frontend"]
|
||||
__all__ = ["Frontend", "env"]
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Access to the project's fastapi-vue environment variables.
|
||||
|
||||
The project entry point (generated __main__.py) sets FASTAPI_VUE to the
|
||||
project-specific prefix (e.g. "MY_APP"). Project settings are then passed
|
||||
as "<PREFIX>_*" environment variables; this module is the single place
|
||||
that resolves those names.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
PREFIX_VARIABLE = "FASTAPI_VUE"
|
||||
|
||||
|
||||
class _Env:
|
||||
"""Lazy accessors for the project's "<PREFIX>_*" environment variables.
|
||||
|
||||
Evaluated on each access. Value accessors return None when FASTAPI_VUE
|
||||
or the variable itself is not set.
|
||||
"""
|
||||
|
||||
@property
|
||||
def prefix(self) -> str | None:
|
||||
"""Return the project prefix from the FASTAPI_VUE environment variable."""
|
||||
return os.environ.get(PREFIX_VARIABLE) or None
|
||||
|
||||
def _get(self, name: str) -> str | None:
|
||||
prefix = self.prefix
|
||||
return os.environ.get(f"{prefix}_{name}") if prefix else None
|
||||
|
||||
@property
|
||||
def dev(self) -> bool:
|
||||
"""Check whether running under the devserver (<PREFIX>_DEV=1)."""
|
||||
return self._get("DEV") == "1"
|
||||
|
||||
@property
|
||||
def vite_url(self) -> str | None:
|
||||
"""Return the vite devserver URL (<PREFIX>_VITE_URL), if set."""
|
||||
return self._get("VITE_URL")
|
||||
|
||||
@property
|
||||
def backend_url(self) -> str | None:
|
||||
"""Return the backend URL (<PREFIX>_BACKEND_URL), if set."""
|
||||
return self._get("BACKEND_URL")
|
||||
|
||||
|
||||
env = _Env()
|
||||
@@ -4,6 +4,7 @@ import asyncio
|
||||
import importlib.metadata
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
from contextlib import suppress
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -11,7 +12,10 @@ from typing import Any
|
||||
import tracerite
|
||||
import uvicorn
|
||||
from uvicorn import Config, Server
|
||||
from uvicorn.main import STARTUP_FAILURE
|
||||
from uvicorn.supervisors import ChangeReload, Multiprocess
|
||||
|
||||
from .environ import env
|
||||
from .hostutil import parse_endpoints
|
||||
from .logging import (
|
||||
install_access_log,
|
||||
@@ -32,14 +36,25 @@ if "FORCE_COLOR" not in os.environ and use_color():
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_WILDCARD_HOSTS = frozenset({"0.0.0.0", "::"}) # noqa: S104
|
||||
_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "::1"})
|
||||
|
||||
|
||||
def _bind_hosts(host: str) -> list[str]:
|
||||
"""Addresses bound for a configured host; localhost binds both loopbacks."""
|
||||
return sorted(_LOOPBACK_HOSTS) if host == "localhost" else [host]
|
||||
|
||||
|
||||
def _connect_url(endpoints: list[dict]) -> str:
|
||||
"""Return a URL the user can connect to for the first TCP endpoint.
|
||||
|
||||
When running under the devserver (<PREFIX>_VITE_URL is set), the vite
|
||||
devserver URL is shown instead, as that is where the page is served.
|
||||
Wildcard binds (0.0.0.0, ::) are shown as localhost, as that is the
|
||||
address a user can actually open. Returns "" for unix-socket-only setups.
|
||||
address a user can actually open. Unix-socket-only setups show plain
|
||||
http://localhost (the typical reverse-proxy target).
|
||||
"""
|
||||
if vite_url := env.vite_url:
|
||||
return vite_url
|
||||
for endpoint in endpoints:
|
||||
host = endpoint.get("host")
|
||||
if host is None:
|
||||
@@ -49,16 +64,34 @@ def _connect_url(endpoints: list[dict]) -> str:
|
||||
elif ":" in host: # IPv6 literal
|
||||
host = f"[{host}]"
|
||||
return f"http://{host}:{endpoint['port']}"
|
||||
return ""
|
||||
return "http://localhost"
|
||||
|
||||
|
||||
def _print_startup_box(template: str, app: str, endpoints: list[dict]) -> None:
|
||||
def _listen_addresses(endpoints: list[dict]) -> str:
|
||||
"""Return space-separated listen addresses as bound (host:port or uds path).
|
||||
|
||||
localhost is expanded to both loopbacks, matching the actual binds.
|
||||
"""
|
||||
parts = []
|
||||
for ep in endpoints:
|
||||
if "uds" in ep:
|
||||
parts.append(ep["uds"])
|
||||
continue
|
||||
for addr in _bind_hosts(ep["host"]):
|
||||
shown = f"[{addr}]" if ":" in addr else addr # bracket IPv6 literals
|
||||
parts.append(f"{shown}:{ep['port']}")
|
||||
return " ".join(dict.fromkeys(parts))
|
||||
|
||||
|
||||
def print_startup_box(template: str, app: str, endpoints: list[dict]) -> None:
|
||||
"""Format the startup box template and print it.
|
||||
|
||||
Available fields: ``{module}`` (top-level package of the app path),
|
||||
``{name}`` (module with spaces instead of underscores), ``{Name}``
|
||||
(also capitalized), ``{version}`` (from installed package metadata,
|
||||
"dev" when not installed) and ``{url}``.
|
||||
"dev" when not installed), ``{listen}`` (space-separated listen
|
||||
addresses as bound, localhost expanded to both loopbacks) and ``{url}``
|
||||
(vite devserver URL when set, else the first connectable backend URL).
|
||||
"""
|
||||
module = app.split(":", 1)[0].split(".", 1)[0]
|
||||
name = module.replace("_", " ")
|
||||
@@ -71,6 +104,7 @@ def _print_startup_box(template: str, app: str, endpoints: list[dict]) -> None:
|
||||
"name": name,
|
||||
"Name": name.title(),
|
||||
"version": version,
|
||||
"listen": _listen_addresses(endpoints),
|
||||
"url": _connect_url(endpoints),
|
||||
}
|
||||
print_box(template.format_map(values))
|
||||
@@ -84,7 +118,7 @@ def run( # noqa: PLR0913
|
||||
reload: bool | Path = False,
|
||||
workers: int | None = None,
|
||||
access_log: bool = True,
|
||||
startup_box: str | None = "{Name} {version}\n{url}",
|
||||
startup_box: str | None = "{Name} {version} @ {listen}\n{url}",
|
||||
log_config: Any = uvicorn.config.LOGGING_CONFIG, # noqa: ANN401
|
||||
**uvicorn_config: Any, # noqa: ANN401
|
||||
) -> None:
|
||||
@@ -101,7 +135,7 @@ def run( # noqa: PLR0913
|
||||
access_log: Enable our colored HTTP/WebSocket access logging middleware
|
||||
(uvicorn's own access logging is always bypassed).
|
||||
startup_box: Template for the startup box printed to stderr before
|
||||
serving (see _print_startup_box for fields), None to not print it.
|
||||
serving (see print_startup_box for fields), None to not print it.
|
||||
log_config: Logging config passed to uvicorn. Dict configs are patched
|
||||
best-effort (see fastapi_vue.logging.patch_log_config): tracerite
|
||||
loading and WebSocket chatter filtering are always installed, and
|
||||
@@ -115,7 +149,7 @@ def run( # noqa: PLR0913
|
||||
raise ValueError(msg)
|
||||
|
||||
if startup_box:
|
||||
_print_startup_box(startup_box, app, endpoints)
|
||||
print_startup_box(startup_box, app, endpoints)
|
||||
|
||||
if isinstance(reload, Path):
|
||||
uvicorn_config["reload_dirs"] = [str(reload)]
|
||||
@@ -143,6 +177,67 @@ def run( # noqa: PLR0913
|
||||
asyncio.run(serve(endpoints, **conf))
|
||||
|
||||
|
||||
def _bind_sockets(endpoints: list[dict]) -> list[socket.socket]:
|
||||
"""Bind sockets for all endpoints, expanding localhost to both loopbacks.
|
||||
|
||||
localhost is bound as 127.0.0.1 and ::1 explicitly, so resolver quirks
|
||||
(notably Windows resolving localhost to ::1 only) cannot make the server
|
||||
unreachable. Addresses that cannot be bound (e.g. IPv6 unavailable) are
|
||||
skipped with a warning; exits only if nothing could be bound.
|
||||
"""
|
||||
sockets: list[socket.socket] = []
|
||||
seen: set = set()
|
||||
for ep in endpoints:
|
||||
if "uds" in ep:
|
||||
uds = ep["uds"]
|
||||
if uds in seen:
|
||||
continue
|
||||
seen.add(uds)
|
||||
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
try:
|
||||
sock.bind(uds)
|
||||
Path(uds).chmod(0o666)
|
||||
except OSError as e:
|
||||
logger.warning("Could not bind unix socket %s: %s", uds, e)
|
||||
sock.close()
|
||||
continue
|
||||
sock.set_inheritable(True)
|
||||
sockets.append(sock)
|
||||
continue
|
||||
|
||||
host, port = ep["host"], ep["port"]
|
||||
for addr in _bind_hosts(host):
|
||||
if (addr, port) in seen:
|
||||
continue
|
||||
seen.add((addr, port))
|
||||
family = socket.AF_INET6 if ":" in addr else socket.AF_INET
|
||||
sock = socket.socket(family, socket.SOCK_STREAM)
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
if family == socket.AF_INET6:
|
||||
with suppress(OSError):
|
||||
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
|
||||
try:
|
||||
sock.bind((addr, port))
|
||||
except OSError as e:
|
||||
logger.warning("Could not bind %s:%d: %s", addr, port, e)
|
||||
sock.close()
|
||||
continue
|
||||
sock.set_inheritable(True)
|
||||
sockets.append(sock)
|
||||
|
||||
if not sockets:
|
||||
logger.error("Could not bind any endpoint")
|
||||
raise SystemExit(STARTUP_FAILURE)
|
||||
return sockets
|
||||
|
||||
|
||||
def _remove_uds_files(endpoints: list[dict]) -> None:
|
||||
"""Remove unix socket files we created (mirrors uvicorn.run cleanup)."""
|
||||
for ep in endpoints:
|
||||
if "uds" in ep:
|
||||
Path(ep["uds"]).unlink(missing_ok=True)
|
||||
|
||||
|
||||
async def serve(endpoints: list[dict], **kwargs: Any) -> None: # noqa: ANN401
|
||||
"""Serve the given endpoints in current process/loop. Does not spawn extra processes."""
|
||||
forbidden = {"reload", "workers"} & {k for k, v in kwargs.items() if v}
|
||||
@@ -151,16 +246,21 @@ async def serve(endpoints: list[dict], **kwargs: Any) -> None: # noqa: ANN401
|
||||
"Options %s have no effect in simple mode (multiple endpoints)",
|
||||
", ".join(sorted(forbidden)),
|
||||
)
|
||||
await asyncio.gather(*(Server(Config(**kwargs, **ep)).serve() for ep in endpoints))
|
||||
try:
|
||||
await Server(Config(**kwargs)).serve(sockets=_bind_sockets(endpoints))
|
||||
finally:
|
||||
_remove_uds_files(endpoints)
|
||||
|
||||
|
||||
def serve_multiprocess(endpoints: list[dict], **kwargs: Any) -> None: # noqa: ANN401
|
||||
"""Serve using uvicorn.run() for reload/workers support. Only first endpoint is used."""
|
||||
if len(endpoints) > 1:
|
||||
eps = [ep["uds"] if "uds" in ep else f"{ep['host']}:{ep['port']}" for ep in endpoints]
|
||||
logger.warning(
|
||||
"Current mode supports only one endpoint. Listening: %s, skipped: %s",
|
||||
eps[0],
|
||||
" ".join(eps[1:]),
|
||||
)
|
||||
uvicorn.run(**kwargs, **endpoints[0])
|
||||
"""Serve using uvicorn supervisors for reload/workers support."""
|
||||
config = Config(**kwargs)
|
||||
server = Server(config)
|
||||
sockets = _bind_sockets(endpoints)
|
||||
try:
|
||||
if config.should_reload:
|
||||
ChangeReload(config, target=server.run, sockets=sockets).run()
|
||||
else:
|
||||
Multiprocess(config, sockets=sockets).run()
|
||||
finally:
|
||||
_remove_uds_files(endpoints)
|
||||
|
||||
@@ -19,6 +19,8 @@ from starlette.exceptions import HTTPException
|
||||
from starlette.routing import Route
|
||||
from zstandard import ZstdCompressor
|
||||
|
||||
from .environ import env
|
||||
|
||||
logger = logging.getLogger("uvicorn.error") # Use FastAPI logging style
|
||||
|
||||
__all__ = ["Frontend"]
|
||||
@@ -287,7 +289,8 @@ class Frontend:
|
||||
|
||||
def _devmode_respond(_request: Request, _name: str = "") -> JSONResponse:
|
||||
"""Return error response directing to Vite server."""
|
||||
at = f" at {env.vite_url}" if env.vite_url else ""
|
||||
return JSONResponse(
|
||||
status_code=409,
|
||||
content={"detail": "[devmode] Use Vite devserver instead."},
|
||||
content={"detail": f"[devmode] Use Vite devserver{at} instead."},
|
||||
)
|
||||
|
||||
+63
-23
@@ -161,7 +161,7 @@ NEW_BUILD_HOOK_PATH = "scripts/fastapi-vue/buildhook.py"
|
||||
# Frontend instantiation block for patching existing apps
|
||||
FRONTEND_BLOCK = """
|
||||
# Vue Frontend static files
|
||||
frontend = Frontend(Path(__file__).with_name("frontend-build"))
|
||||
frontend = fastapi_vue.Frontend(Path(__file__).with_name("frontend-build"))
|
||||
"""
|
||||
|
||||
# Lifespan block for patching apps that don't have one
|
||||
@@ -473,8 +473,8 @@ def _find_app_in_subpackage(subpkg_dir: Path) -> tuple[Path, str] | None:
|
||||
return None
|
||||
|
||||
|
||||
def _add_devmode_to_main(content: str) -> str:
|
||||
"""Add DEVMODE variable to an existing main module."""
|
||||
def _add_env_prefix_to_main(content: str) -> str:
|
||||
"""Add FASTAPI_VUE environment prefix setup to an existing main module."""
|
||||
lines = content.splitlines()
|
||||
|
||||
# Check if os is imported
|
||||
@@ -489,7 +489,7 @@ def _add_devmode_to_main(content: str) -> str:
|
||||
elif stripped and not stripped.startswith("#"):
|
||||
break
|
||||
|
||||
# Insert imports and DEVMODE after existing imports
|
||||
# Insert imports and env setup after existing imports
|
||||
new_lines = []
|
||||
if not has_os_import:
|
||||
new_lines.append("import os")
|
||||
@@ -497,7 +497,7 @@ def _add_devmode_to_main(content: str) -> str:
|
||||
[
|
||||
"",
|
||||
"# Added by fastapi-vue-setup",
|
||||
'DEVMODE = os.getenv("ENVPREFIX_DEV") == "1"',
|
||||
'os.environ["FASTAPI_VUE"] = "ENVPREFIX"',
|
||||
"",
|
||||
]
|
||||
)
|
||||
@@ -597,11 +597,35 @@ def render_template(template: str, **kwargs: str) -> str:
|
||||
return result
|
||||
|
||||
|
||||
def patch_app_file(path: Path, main_module_path: str, app_var: str, *, dry: bool = False) -> bool:
|
||||
def needs_app_migration(project_dir: Path) -> bool:
|
||||
"""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
|
||||
a DEVMODE import from the main module; 1.6+ uses fastapi_vue.Frontend and
|
||||
fastapi_vue.env. Must be called before the dependency step rewrites the
|
||||
fastapi-vue requirement in pyproject.toml.
|
||||
"""
|
||||
pyproject = project_dir / "pyproject.toml"
|
||||
if not pyproject.exists():
|
||||
return False
|
||||
data = tomlkit.parse(pyproject.read_text("UTF-8"))
|
||||
for dep in data.get("project", {}).get("dependencies", []):
|
||||
match = re.match(r"\s*fastapi-vue(?:\[[^\]]*\])?\s*(.*)", str(dep))
|
||||
if match:
|
||||
version = re.search(r"(\d+)\.(\d+)", match.group(1))
|
||||
return version is not None and (int(version[1]), int(version[2])) < (1, 6)
|
||||
return False
|
||||
|
||||
|
||||
def patch_app_file(
|
||||
path: Path, main_module_path: str, app_var: str, *, migrate: bool = False, dry: bool = False
|
||||
) -> bool:
|
||||
"""Patch an existing app.py with frontend integration.
|
||||
|
||||
Inserts imports at top (ruff will sort them), route at bottom,
|
||||
and tries to patch lifespan with frontend.load().
|
||||
and tries to patch lifespan with frontend.load(). With migrate=True,
|
||||
pre-1.6 patching (plain Frontend, DEVMODE import) is first rewritten
|
||||
to the current format.
|
||||
|
||||
Returns True if patched, False if already patched or failed.
|
||||
"""
|
||||
@@ -612,24 +636,38 @@ def patch_app_file(path: Path, main_module_path: str, app_var: str, *, dry: bool
|
||||
original_content = path.read_text("UTF-8")
|
||||
content = original_content
|
||||
|
||||
# Check what's already patched
|
||||
has_frontend = "from fastapi_vue import Frontend" in content
|
||||
has_devmode = f"from {main_module_path} import DEVMODE" in content
|
||||
# Migrate pre-1.6 patching to the current format: Frontend via the
|
||||
# fastapi_vue module, DEVMODE via fastapi_vue.env
|
||||
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"
|
||||
if old_import in content:
|
||||
has_plain_import = re.search(r"^import fastapi_vue$", content, re.MULTILINE)
|
||||
content = content.replace(old_import, "" if has_plain_import else "import fastapi_vue")
|
||||
content = content.replace("debug=DEVMODE", "debug=fastapi_vue.env.dev")
|
||||
|
||||
# Check what's already patched; plain "Frontend(" so user modifications
|
||||
# of the integration (renames, different call shape) still count
|
||||
has_frontend = "Frontend(" in content
|
||||
has_debug_arg = re.search(r"FastAPI\s*\([^)]*debug\s*=", content) is not None
|
||||
has_lifespan = "await frontend.load()" in content
|
||||
|
||||
if has_frontend and has_devmode and has_debug_arg and has_lifespan:
|
||||
already_patched = has_frontend and has_debug_arg and has_lifespan
|
||||
if content == original_content and already_patched:
|
||||
print(f"✔️ {path} (already patched)")
|
||||
return False
|
||||
|
||||
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
|
||||
imports = []
|
||||
if not has_frontend:
|
||||
imports.extend(["from pathlib import Path", "from fastapi_vue import Frontend"])
|
||||
if not has_devmode:
|
||||
imports.append(f"from {main_module_path} import DEVMODE")
|
||||
imports.append("from pathlib import Path")
|
||||
if not re.search(r"^import fastapi_vue$", content, re.MULTILINE):
|
||||
imports.append("import fastapi_vue")
|
||||
if imports:
|
||||
insert_line = find_import_insertion_line(content)
|
||||
lines = content.splitlines(keepends=True)
|
||||
@@ -664,14 +702,14 @@ def patch_app_file(path: Path, main_module_path: str, app_var: str, *, dry: bool
|
||||
lines.append(route_line)
|
||||
content = "\n".join(lines)
|
||||
|
||||
# Try to patch FastAPI() call with debug=DEVMODE if no debug arg exists
|
||||
# Try to patch FastAPI() call with debug=fastapi_vue.env.dev if no debug arg exists
|
||||
if not has_debug_arg:
|
||||
fastapi_pattern = r"(\w+\s*=\s*FastAPI\s*\()([^)]*)\)"
|
||||
for match in re.finditer(fastapi_pattern, content, re.DOTALL):
|
||||
args = match.group(2)
|
||||
if "debug" not in args:
|
||||
# Add debug=DEVMODE as last argument
|
||||
new_args = f"{args}, debug=DEVMODE" if args.strip() else "debug=DEVMODE"
|
||||
# Add debug=fastapi_vue.env.dev as last argument
|
||||
new_args = (f"{args}, " if args.strip() else "") + "debug=fastapi_vue.env.dev"
|
||||
content = (
|
||||
content[: match.start()]
|
||||
+ match.group(1)
|
||||
@@ -1316,7 +1354,7 @@ def cmd_setup(args: argparse.Namespace) -> int:
|
||||
# Check if project already has a CLI entrypoint in pyproject.toml
|
||||
existing_cli_module = _find_existing_cli_module_path(project_dir, module_name)
|
||||
|
||||
# Determine main module path for DEVMODE import
|
||||
# Determine main module path (for migrating old DEVMODE imports)
|
||||
main_module_path = existing_cli_module or f"{module_name}.__main__"
|
||||
if existing_cli_module:
|
||||
print(f"ℹ️ Using existing CLI: {existing_cli_module}")
|
||||
@@ -1463,7 +1501,9 @@ def cmd_setup(args: argparse.Namespace) -> int:
|
||||
# === Handle app module ===
|
||||
if app_file:
|
||||
# Existing app: patch with import, route, and try to patch lifespan
|
||||
patch_app_file(app_file, main_module_path, app_var, dry=dry)
|
||||
patch_app_file(
|
||||
app_file, main_module_path, app_var, migrate=needs_app_migration(project_dir), dry=dry
|
||||
)
|
||||
else:
|
||||
# No app: create full app.py
|
||||
# Create __init__.py if missing
|
||||
@@ -1509,7 +1549,7 @@ def cmd_setup(args: argparse.Namespace) -> int:
|
||||
)
|
||||
else:
|
||||
# Existing CLI entrypoint: write our template as .new.py beside the existing module
|
||||
# and also patch the existing module with DEVMODE if needed
|
||||
# and also patch the existing module with FASTAPI_VUE setup if needed
|
||||
_write_fallback_file(
|
||||
main,
|
||||
main_fallback,
|
||||
@@ -1519,8 +1559,8 @@ def cmd_setup(args: argparse.Namespace) -> int:
|
||||
)
|
||||
if main.exists():
|
||||
content = main.read_text("UTF-8")
|
||||
if "DEVMODE" not in content:
|
||||
new_content = _add_devmode_to_main(content)
|
||||
if "FASTAPI_VUE" not in content:
|
||||
new_content = _add_env_prefix_to_main(content)
|
||||
new_file = main.with_suffix(".new.py")
|
||||
_write_fallback_file(
|
||||
main,
|
||||
|
||||
@@ -5,10 +5,11 @@ import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import fastapi_vue
|
||||
from fastapi_vue import server
|
||||
|
||||
DEFAULT_PORT = TEMPLATE_DEFAULT_PORT
|
||||
DEVMODE = os.getenv("ENVPREFIX_DEV") == "1"
|
||||
os.environ["FASTAPI_VUE"] = "ENVPREFIX"
|
||||
|
||||
|
||||
def main() -> None:
|
||||
@@ -26,7 +27,7 @@ def main() -> None:
|
||||
listen=args.listen,
|
||||
default_port=DEFAULT_PORT,
|
||||
server_header=False,
|
||||
reload=Path(__file__).parent if DEVMODE else False,
|
||||
reload=Path(__file__).parent if fastapi_vue.env.dev else False,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -4,12 +4,11 @@ from collections.abc import AsyncGenerator
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
import fastapi_vue
|
||||
from fastapi import FastAPI
|
||||
from fastapi_vue import Frontend
|
||||
from MAIN_MODULE import DEVMODE
|
||||
|
||||
# Vue Frontend static files
|
||||
frontend = Frontend(Path(__file__).with_name("frontend-build"))
|
||||
frontend = fastapi_vue.Frontend(Path(__file__).with_name("frontend-build"))
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
@@ -19,7 +18,7 @@ async def lifespan(_app: FastAPI) -> AsyncGenerator:
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title="PROJECT_TITLE", debug=DEVMODE, lifespan=lifespan)
|
||||
app = FastAPI(title="PROJECT_TITLE", debug=fastapi_vue.env.dev, lifespan=lifespan)
|
||||
|
||||
|
||||
# Add API routes here...
|
||||
|
||||
@@ -8,11 +8,11 @@
|
||||
* - Disables Vite's screen clearing on startup
|
||||
*
|
||||
* Options:
|
||||
* paths - Array of paths to proxy (default: ["/api"])
|
||||
* paths - Array of paths to proxy (default: ['/api'])
|
||||
*/
|
||||
|
||||
export default function fastapiVue({ paths = ["/api"] } = {}) {
|
||||
const backendUrl = process.env.ENVPREFIX_BACKEND_URL || "http://localhost:TEMPLATE_DEV_PORT"
|
||||
export default function fastapiVue({ paths = ['/api'] } = {}) {
|
||||
const backendUrl = process.env.ENVPREFIX_BACKEND_URL || 'http://localhost:TEMPLATE_DEV_PORT'
|
||||
|
||||
// Build proxy configuration for each path
|
||||
const proxy = {}
|
||||
@@ -25,12 +25,12 @@ export default function fastapiVue({ paths = ["/api"] } = {}) {
|
||||
}
|
||||
|
||||
return {
|
||||
name: "vite-plugin-fastapi-MODULE_NAME",
|
||||
name: 'vite-plugin-fastapi-MODULE_NAME',
|
||||
config: () => ({
|
||||
clearScreen: false,
|
||||
server: { proxy },
|
||||
build: {
|
||||
outDir: "../MODULE_NAME/frontend-build",
|
||||
outDir: '../MODULE_NAME/frontend-build',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -1,19 +1,23 @@
|
||||
# ruff: noqa: INP001
|
||||
"""Utilities meant for devserver script, used only in source repository with dev deps."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from asyncio.subprocess import Process
|
||||
from collections.abc import Awaitable
|
||||
from contextlib import suppress
|
||||
from pathlib import Path
|
||||
from subprocess import CalledProcessError
|
||||
from typing import Any
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from buildutil import find_dev_tool, find_install_tool, logger
|
||||
from fastapi_vue.hostutil import parse_endpoint
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Awaitable
|
||||
|
||||
|
||||
class ProcessGroup(asyncio.TaskGroup):
|
||||
"""TaskGroup with structured ownership of async subprocesses."""
|
||||
@@ -122,7 +126,7 @@ async def ready(url: str, path: str = "", max_attempts: int = 50) -> None:
|
||||
"""Wait for the server to be ready by polling an endpoint.
|
||||
|
||||
Use empty path to disable the check and make this return immediately.
|
||||
Raises TimeoutError if server doesn't start in time.
|
||||
Logs, then raises RuntimeError if the server doesn't start in time.
|
||||
"""
|
||||
if not path:
|
||||
return
|
||||
@@ -132,7 +136,8 @@ async def ready(url: str, path: str = "", max_attempts: int = 50) -> None:
|
||||
logger.info("✓ Backend ready!")
|
||||
return
|
||||
if attempt == max_attempts - 1:
|
||||
raise TimeoutError(f"Backend at {url} didn't start in time") # noqa: EM102, TRY003
|
||||
logger.error("Backend at %s didn't start in time", url)
|
||||
raise RuntimeError(url)
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user