♻️ Provide project.configure_app
This commit is contained in:
parent
6089f950b6
commit
f74b20a19f
2 changed files with 20 additions and 7 deletions
|
|
@ -35,6 +35,7 @@ def serve(root: str = ".", host="127.0.0.1", port=8000):
|
|||
project_path = Path(root)
|
||||
project = runtime.Project(project_path)
|
||||
app_instance = project.app()
|
||||
app_instance = project.configure_app(app_instance)
|
||||
uvicorn.run(app_instance, host=host, port=int(port), reload=False)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -72,23 +72,35 @@ class Project:
|
|||
def is_app_installed(self, name: str) -> bool:
|
||||
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,
|
||||
and register ORM lifecycle event handlers.
|
||||
Create and return a FastAPI app.
|
||||
"""
|
||||
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 router in app_def.routers:
|
||||
app.include_router(router)
|
||||
|
||||
# Startup / shutdown events
|
||||
# Initialize ORM on startup
|
||||
@app.on_event("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")
|
||||
async def _shutdown():
|
||||
await self.close_orm()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue