|
| 1 | +from contextlib import asynccontextmanager |
| 2 | + |
| 3 | +from fastapi import FastAPI |
| 4 | + |
| 5 | +from app.interface_adapters import api_router |
| 6 | +from app.interface_adapters.containers import Container |
| 7 | +from app.interface_adapters.exceptions import AppException |
| 8 | +from app.interface_adapters.middleware.error_handler import app_exception_handler |
| 9 | +from app.resource_adapters.persistence.sqlmodel.database import get_engine |
| 10 | +from config import settings |
| 11 | + |
| 12 | + |
| 13 | +def create_container(): |
| 14 | + container = Container() |
| 15 | + container.wire(packages=["app"]) |
| 16 | + return container |
| 17 | + |
| 18 | + |
| 19 | +def create_app(lifespan_handler=None) -> FastAPI: |
| 20 | + if lifespan_handler is None: |
| 21 | + |
| 22 | + @asynccontextmanager |
| 23 | + async def default_lifespan(app: FastAPI): |
| 24 | + # Initialize container and wire dependencies |
| 25 | + container = create_container() |
| 26 | + |
| 27 | + # Initialize database if using SQLModel |
| 28 | + get_engine() |
| 29 | + |
| 30 | + app.state.running = True |
| 31 | + |
| 32 | + yield |
| 33 | + |
| 34 | + app.state.running = False |
| 35 | + container.unwire() |
| 36 | + |
| 37 | + lifespan_handler = default_lifespan |
| 38 | + |
| 39 | + app = FastAPI( |
| 40 | + lifespan=lifespan_handler, |
| 41 | + title=settings.project_name, |
| 42 | + openapi_url="/v1/openapi.json", |
| 43 | + ) |
| 44 | + |
| 45 | + # Register global exception handler |
| 46 | + app.add_exception_handler(AppException, app_exception_handler) |
| 47 | + |
| 48 | + # Register routes |
| 49 | + app.include_router(api_router, prefix="/v1") |
| 50 | + |
| 51 | + return app |
0 commit comments