♻️ Provide project.configure_app

This commit is contained in:
Brian Wiborg 2025-10-02 04:50:55 +02:00
parent 6089f950b6
commit f74b20a19f
No known key found for this signature in database
2 changed files with 20 additions and 7 deletions

View file

@ -35,6 +35,7 @@ def serve(root: str = ".", host="127.0.0.1", port=8000):
project_path = Path(root) project_path = Path(root)
project = runtime.Project(project_path) project = runtime.Project(project_path)
app_instance = project.app() app_instance = project.app()
app_instance = project.configure_app(app_instance)
uvicorn.run(app_instance, host=host, port=int(port), reload=False) uvicorn.run(app_instance, host=host, port=int(port), reload=False)

View file

@ -72,23 +72,35 @@ class Project:
def is_app_installed(self, name: str) -> bool: def is_app_installed(self, name: str) -> bool:
return name in getattr(self.settings, "INSTALLED_APPS", []) return name in getattr(self.settings, "INSTALLED_APPS", [])
def app(self, generate_schemas: bool = False) -> FastAPI: def app(self,
docs_url: str = "/docs",
) -> FastAPI:
""" """
Create a FastAPI app, attach all APIRouters from registered apps, Create and return a FastAPI app.
and register ORM lifecycle event handlers.
""" """
app = FastAPI(title=getattr(self.settings, "PROJECT_NAME", "OhMyAPI Project")) import ohmyapi
return FastAPI(
title=getattr(self.settings, "PROJECT_NAME", "OhMyAPI Project"),
description=getattr(self.settings, "PROJECT_DESCRIPTION", ""),
docs_url=getattr(self.settings, "DOCS_URL", "/docs"),
version=ohmyapi.__VERSION__,
)
# Attach routers from apps def configure_app(self, app: FastAPI) -> FastAPI:
"""
Attach project routes and event handlers to given FastAPI instance.
"""
# Attach project routes.
for app_name, app_def in self._apps.items(): for app_name, app_def in self._apps.items():
for router in app_def.routers: for router in app_def.routers:
app.include_router(router) app.include_router(router)
# Startup / shutdown events # Initialize ORM on startup
@app.on_event("startup") @app.on_event("startup")
async def _startup(): async def _startup():
await self.init_orm(generate_schemas=generate_schemas) await self.init_orm(generate_schemas=False)
# Close ORM on shutdown
@app.on_event("shutdown") @app.on_event("shutdown")
async def _shutdown(): async def _shutdown():
await self.close_orm() await self.close_orm()