Refactor with new fastapi-vue utility module to run the server, used in CLI main and devserver to run the main app. Default ports made part of templating, so that --ports can be easily specified to fastapi-vue-setup to customize (respects earlier choices when no --ports is specified). New overall default ports 3100, 3200.
This commit is contained in:
@@ -9,6 +9,8 @@ import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi_vue import server
|
||||
|
||||
# Import util.py from scripts/fastapi-vue (not a package, so we adjust sys.path)
|
||||
sys.path.insert(0, str(Path(__file__).with_name("fastapi-vue")))
|
||||
from devutil import ( # type: ignore
|
||||
@@ -20,6 +22,9 @@ from devutil import ( # type: ignore
|
||||
setup_vite,
|
||||
)
|
||||
|
||||
DEFAULT_VITE_PORT = TEMPLATE_VITE_PORT
|
||||
DEFAULT_DEV_PORT = TEMPLATE_DEV_PORT
|
||||
|
||||
|
||||
async def run_devserver(frontend: str, backend: str) -> None:
|
||||
reporoot = Path(__file__).parent.parent
|
||||
@@ -28,8 +33,10 @@ async def run_devserver(frontend: str, backend: str) -> None:
|
||||
logger.warning("Frontend source not found at %s", front)
|
||||
raise SystemExit(1)
|
||||
|
||||
viteurl, npm_install, vite = setup_vite(frontend)
|
||||
backurl, fastapi = setup_fastapi(backend, "MODULE_NAME.APP_MODULE:APP_VAR")
|
||||
viteurl, npm_install, vite = setup_vite(frontend, DEFAULT_VITE_PORT)
|
||||
backurl, module, backend_config = setup_fastapi(
|
||||
backend, "MODULE_NAME.APP_MODULE:APP_VAR", DEFAULT_DEV_PORT
|
||||
)
|
||||
|
||||
# Tell the everyone where the frontend and backend are (vite proxy, etc)
|
||||
os.environ["FASTAPI_VUE_FRONTEND_URL"] = viteurl
|
||||
@@ -38,13 +45,10 @@ async def run_devserver(frontend: str, backend: str) -> None:
|
||||
async with ProcessGroup() as pg:
|
||||
npm_i = await pg.spawn(*npm_install, cwd=front)
|
||||
await check_ports_free(viteurl, backurl)
|
||||
await pg.spawn(
|
||||
*fastapi,
|
||||
"--reload",
|
||||
"--reload-dir=MODULE_NAME", # Don't reload on frontend changes
|
||||
"--forwarded-allow-ips=*",
|
||||
cwd=reporoot,
|
||||
)
|
||||
|
||||
# Run backend in a thread (server.run is blocking)
|
||||
loop = asyncio.get_event_loop()
|
||||
loop.run_in_executor(None, lambda: server.run(module, **backend_config))
|
||||
|
||||
# Wait for both install and backend to be ready
|
||||
await pg.wait(npm_i, ready(backurl, path="/api/health?from=devserver.py"))
|
||||
@@ -63,12 +67,12 @@ def main():
|
||||
"frontend",
|
||||
nargs="?",
|
||||
metavar="host:port",
|
||||
help="Vite frontend endpoint (default: localhost:5173)",
|
||||
help=f"Vite frontend endpoint (default: localhost:{DEFAULT_VITE_PORT})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--backend",
|
||||
metavar="host:port",
|
||||
help="FastAPI backend endpoint (default: localhost:5180)",
|
||||
help=f"FastAPI backend endpoint (default: localhost:{DEFAULT_DEV_PORT})",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
with contextlib.suppress(KeyboardInterrupt):
|
||||
|
||||
@@ -11,9 +11,6 @@ import httpx
|
||||
from buildutil import find_dev_tool, find_install_tool, logger
|
||||
from fastapi_vue.hostutil import parse_endpoint
|
||||
|
||||
DEFAULT_VITE_PORT = 5173
|
||||
DEFAULT_BACKEND_PORT = 5180
|
||||
|
||||
|
||||
class ProcessGroup:
|
||||
"""Manage async subprocesses with automatic cleanup, like TaskGroup for processes."""
|
||||
@@ -134,13 +131,15 @@ async def ready(url: str, path: str = "") -> None:
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
|
||||
def setup_vite(endpoint: str) -> tuple[str, list[str], list[str]]:
|
||||
def setup_vite(
|
||||
endpoint: str, default_port: int = 5173
|
||||
) -> tuple[str, list[str], list[str]]:
|
||||
"""Parse frontend endpoint and build commands.
|
||||
|
||||
Returns (url, install_cmd, dev_cmd).
|
||||
Raises SystemExit(1) on invalid config.
|
||||
"""
|
||||
endpoints = parse_endpoint(endpoint, DEFAULT_VITE_PORT)
|
||||
endpoints = parse_endpoint(endpoint, default_port)
|
||||
|
||||
if "uds" in endpoints[0]:
|
||||
logger.warning("Unix sockets not supported with vite devserver")
|
||||
@@ -153,18 +152,17 @@ def setup_vite(endpoint: str) -> tuple[str, list[str], list[str]]:
|
||||
dev_cmd = find_dev_tool()
|
||||
if host != "localhost":
|
||||
dev_cmd.append("--host" if len(endpoints) > 1 else f"--host={host}")
|
||||
if port != 5173:
|
||||
dev_cmd.append(f"--port={port}")
|
||||
dev_cmd.append(f"--port={port}")
|
||||
|
||||
return f"http://{host}:{port}", install_cmd, dev_cmd
|
||||
|
||||
|
||||
def setup_fastapi(
|
||||
endpoint: str, module: str, default_port: int = DEFAULT_BACKEND_PORT
|
||||
) -> tuple[str, list[str]]:
|
||||
"""Parse backend endpoint and build fastapi dev command.
|
||||
endpoint: str, module: str, default_port: int = 8000
|
||||
) -> tuple[str, str, dict]:
|
||||
"""Parse backend endpoint and build server.run() config.
|
||||
|
||||
Returns (url, cmd).
|
||||
Returns (url, module, config_dict).
|
||||
Raises SystemExit(1) on invalid config.
|
||||
"""
|
||||
endpoints = parse_endpoint(endpoint, default_port)
|
||||
@@ -176,14 +174,10 @@ def setup_fastapi(
|
||||
host = endpoints[0]["host"]
|
||||
port = endpoints[0]["port"]
|
||||
|
||||
cmd = [
|
||||
"fastapi",
|
||||
"dev",
|
||||
"--entrypoint",
|
||||
module,
|
||||
"--host",
|
||||
host,
|
||||
"--port",
|
||||
str(port),
|
||||
]
|
||||
return f"http://{host}:{port}", cmd
|
||||
config = {
|
||||
"listen": f"{host}:{port}",
|
||||
"reload": True,
|
||||
"reload_dirs": [module.split(".")[0]], # Don't reload on frontend changes
|
||||
"forwarded_allow_ips": "*",
|
||||
}
|
||||
return f"http://{host}:{port}", module, config
|
||||
|
||||
Reference in New Issue
Block a user