This is How I implement the DB connection (PostgreSQL):
class DBContext(object):
def __init__(self, session=None):
self._engine = create_engine(POSTGRES_URL)
self._session: Session = session or scoped_session(sessionmaker(
autocommit=False, autoflush=False, bind=self._engine))
self.extrnal_session = True if session else False
self.current_session: Session = None
def start_session(self):
self.current_session = self._session
def begin_transaction(self):
try:
self.current_session.begin()
except:
pass
def commit(self):
if not self.extrnal_session:
self.current_session.commit()
def end_session(self):
if self.current_session and not self.extrnal_session:
self.current_session.close()
@contextmanager
def db_session(self):
try:
self.start_session()
yield self.current_session
finally:
self.end_session()
And in one of the endpoints in my FastAPI
app I have something like this:
@router.get(
"/user/{uuid}/item/",
# dependencies=[Depends(auth)],
response_model=GuestResponseSerializer,
responses={
404: {"model": ResponseSerializer}
}
)
def get_user(uuid: UUID):
retries = 0
row = None
while retries < 10:
print("try number", retries, uuid)
db = DBContext()
db.start_session()
query = db.current_session.query(Guest)
query = query.filter(Guest.uuid == uuid)
row = query.first()
if row:
break
retries += 1
if not row:
return JSONResponse({"message": "not found"}, status_code=404)
guest = GuestEntity.from_orm(row)
return guest
It was so weird. It does not fetch the user with the UUID the first time and it gets in the while loop and sometimes it takes 5 times to get the same row. I don’t know how it occurs!! And how to fix it.
Output logs:
try number 0 c0813595-7328-4f94-9951-767792553496
try number 1 c0813595-7328-4f94-9951-767792553496
try number 2 c0813595-7328-4f94-9951-767792553496
try number 3 c0813595-7328-4f94-9951-767792553496
try number 4 c0813595-7328-4f94-9951-767792553496
try number 5 c0813595-7328-4f94-9951-767792553496
try number 6 c0813595-7328-4f94-9951-767792553496
try number 7 c0813595-7328-4f94-9951-767792553496
try number 8 c0813595-7328-4f94-9951-767792553496
try number 9 c0813595-7328-4f94-9951-767792553496
INFO: 172.18.0.13:36090 - "GET /v1/user/c0813595-7328-4f94-9951-767792553496/item/ HTTP/1.0" 200 OK