Skip to content

Commit

Permalink
add refresher middleware to close connections after a call and add po…
Browse files Browse the repository at this point in the history
…ol_pre_ping when creating the connection engine (#304)
  • Loading branch information
shincap8 authored Sep 13, 2024
1 parent 89aa3b3 commit 2a7a246
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
5 changes: 4 additions & 1 deletion backend/app/infrastructure/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,13 @@

import os

import uuid
from dotenv import load_dotenv
from sqlalchemy import MetaData, create_engine
from sqlalchemy.orm import sessionmaker

from app.infrastructure.utils.singleton import Singleton


load_dotenv()

Expand All @@ -28,7 +31,7 @@

class Connection:
def __init__(self) -> None:
self.engine = create_engine(CONNECTION_URI, echo=False)
self.engine = create_engine(CONNECTION_URI, echo=False, pool_pre_ping=True)
self.Session = sessionmaker(bind=self.engine, expire_on_commit=False)
self.session = self.Session()
self.metadata = MetaData()
Expand Down
20 changes: 20 additions & 0 deletions backend/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
user,
)
from app.api.endpoints.builder_and_evaluation import evaluation
from app.infrastructure.connection import Connection


load_dotenv()
Expand Down Expand Up @@ -72,3 +73,22 @@ def read_root():
historical_data.router, prefix="/historical_data", tags=["historical_data"]
)
app.include_router(round.router, prefix="/round", tags=["round"])


class RefreshSessionMiddleware:
"""
Refreshes SQLAlchemy session on each call.
There may be issues since close_session is blocking and it is ran in an async function.
Possibly blocking the main asyncio loop.
Keep in mind that middlewares run on the main asyncio thread.
"""

def __init__(self, app):
self.app = app

async def __call__(self, scope, receive, send):
await self.app(scope, receive, send)
Connection().close_session()


app.add_middleware(RefreshSessionMiddleware)

0 comments on commit 2a7a246

Please sign in to comment.