| 1 |
import os |
| 2 |
from typing import cast |
| 3 |
|
| 4 |
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine |
| 5 |
|
| 6 |
from litestar import Litestar |
| 7 |
|
| 8 |
DB_URI = os.environ.get("DATABASE_URI", "postgresql+asyncpg://postgres:[email protected]:5432/db") |
| 9 |
|
| 10 |
|
| 11 |
def get_db_connection(app: Litestar) -> AsyncEngine: |
| 12 |
"""Returns the db engine. |
| 13 |
|
| 14 |
If it doesn't exist, creates it and saves it in on the application state object |
| 15 |
""" |
| 16 |
if not getattr(app.state, "engine", None): |
| 17 |
app.state.engine = create_async_engine(DB_URI) |
| 18 |
return cast("AsyncEngine", app.state.engine) |
| 19 |
|
| 20 |
|
| 21 |
async def close_db_connection(app: Litestar) -> None: |
| 22 |
"""Closes the db connection stored in the application State object.""" |
| 23 |
if getattr(app.state, "engine", None): |
| 24 |
await cast("AsyncEngine", app.state.engine).dispose() |
| 25 |
|
| 26 |
|
| 27 |
app = Litestar(on_startup=[get_db_connection], on_shutdown=[close_db_connection]) |