Code: Select all
from contextvars import ContextVar
from fastapi import FastAPI, BackgroundTasks
from sqlalchemy import text
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
engine = create_async_engine("postgresql+asyncpg://postgres:postgres@localhost:5433/postgres", isolation_level="AUTOCOMMIT")
session_context = ContextVar("session")
app = FastAPI()
class Repository:
async def get_one(self):
return await self.execute(text("select 1"))
async def get_two(self):
return await self.execute(text("select 2"))
async def execute(self, statement):
try:
session = session_context.get()
except LookupError:
session = AsyncSession(engine)
session_context.set(session)
print(session)
result = (await session.execute(statement)).scalar()
await session.close() # for some reason I need to close session every time
return result
async def check_connections_statuses():
print(engine.pool.status())
print(session_context.get())
@app.get("/")
async def main(background_tasks: BackgroundTasks):
repo = Repository()
print(await repo.get_one())
print(await repo.get_two())
background_tasks.add_task(check_connections_statuses)
Code: Select all
1
2
INFO: 127.0.0.1:59836 - "GET / HTTP/1.1" 200 OK
Pool size: 5 Connections in pool: 1 Current Overflow: -4 Current Checked out connections: 0