Refactor to use async database model
This commit is contained in:
@ -13,30 +13,32 @@ from fastapi.encoders import jsonable_encoder
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from sqlalchemy import Engine
|
||||
from sqlalchemy.ext.asyncio import AsyncEngine
|
||||
|
||||
|
||||
from .models import init_db
|
||||
from .models import init_db_async
|
||||
from .backend_api import get_backend_api
|
||||
from .db import setup_database
|
||||
from .db import setup_database, get_async_engine
|
||||
|
||||
from .settings import BackendSettings
|
||||
from .types import DBSessionDep
|
||||
from .types import AsyncDBSessionDep
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def init_backend_app(engine: Engine, get_db_session: DBSessionDep) -> FastAPI:
|
||||
def init_backend_app(settings: BackendSettings) -> FastAPI:
|
||||
"""Initialize backend app."""
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
"""Create database before starting the server."""
|
||||
LOG.debug("Running lifespan")
|
||||
init_db(engine)
|
||||
engine = get_async_engine(settings.async_db_url)
|
||||
await init_db_async(engine)
|
||||
yield
|
||||
|
||||
app = FastAPI(lifespan=lifespan)
|
||||
app.include_router(get_backend_api(get_db_session))
|
||||
app.include_router(get_backend_api(settings))
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_exception_handler(
|
||||
@ -60,6 +62,4 @@ def init_backend_app(engine: Engine, get_db_session: DBSessionDep) -> FastAPI:
|
||||
def create_backend_app(settings: BackendSettings) -> FastAPI:
|
||||
"""Create the backend app."""
|
||||
|
||||
engine, get_db_session = setup_database(settings.db_url)
|
||||
|
||||
return init_backend_app(engine, get_db_session)
|
||||
return init_backend_app(settings)
|
||||
|
||||
Reference in New Issue
Block a user