Skip to content

Commit 312db8c

Browse files
adding asyncpg to director-v2
1 parent c83d60c commit 312db8c

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,25 @@
11
from fastapi import FastAPI
22
from settings_library.postgres import PostgresSettings
33

4+
from ._asyncpg import (
5+
asyncpg_close_db_connection,
6+
asyncpg_connect_to_db,
7+
get_asyncpg_engine,
8+
)
49
from .events import close_db_connection, connect_to_db
510

611

712
def setup(app: FastAPI, settings: PostgresSettings) -> None:
813
async def on_startup() -> None:
914
await connect_to_db(app, settings)
15+
await asyncpg_connect_to_db(app, settings)
1016

1117
async def on_shutdown() -> None:
18+
await asyncpg_close_db_connection(app)
1219
await close_db_connection(app)
1320

1421
app.add_event_handler("startup", on_startup)
1522
app.add_event_handler("shutdown", on_shutdown)
23+
24+
25+
__all__: tuple[str, ...] = ("get_asyncpg_engine",)
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import logging
2+
3+
from fastapi import FastAPI
4+
from servicelib.db_asyncpg_utils import create_async_engine_and_pg_database_ready
5+
from servicelib.logging_utils import log_context
6+
from settings_library.postgres import PostgresSettings
7+
from simcore_postgres_database.utils_aiosqlalchemy import get_pg_engine_stateinfo
8+
9+
_logger = logging.getLogger(__name__)
10+
11+
12+
async def asyncpg_connect_to_db(app: FastAPI, settings: PostgresSettings) -> None:
13+
with log_context(
14+
_logger,
15+
logging.DEBUG,
16+
f"Connecting and migraging {settings.dsn_with_async_sqlalchemy}",
17+
):
18+
engine = await create_async_engine_and_pg_database_ready(settings)
19+
20+
app.state.asyncpg_engine = engine
21+
_logger.debug(
22+
"Setup engine: %s",
23+
await get_pg_engine_stateinfo(engine),
24+
)
25+
26+
27+
async def asyncpg_close_db_connection(app: FastAPI) -> None:
28+
with log_context(
29+
_logger, logging.DEBUG, f"db disconnect of {app.state.asyncpg_engine}"
30+
):
31+
if engine := app.state.asyncpg_engine:
32+
await engine.dispose()
33+
34+
35+
def get_asyncpg_engine(app: FastAPI):
36+
return app.state.asyncpg_engine

0 commit comments

Comments
 (0)