Skip to content

Commit

Permalink
Use asyncio Lock when db_reset=True
Browse files Browse the repository at this point in the history
  • Loading branch information
albireox committed Aug 3, 2024
1 parent 1230e5e commit 8fed729
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions python/valis/db/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# -*- coding: utf-8 -*-
#

import asyncio
from contextvars import ContextVar

import peewee
Expand All @@ -18,7 +19,7 @@
db_state = ContextVar("db_state", default=db_state_default.copy())


def reset_db_state():
async def reset_db_state():
""" Sub-dependency for get_db that resets the context connection state """

from valis.main import settings
Expand Down Expand Up @@ -68,19 +69,22 @@ def connect_db(db, orm: str = 'peewee'):

return db

def get_pw_db(db_state=Depends(reset_db_state)):
async def get_pw_db(db_state=Depends(reset_db_state)):
""" Dependency to connect a database with peewee """

from valis.main import settings

# connect to the db, yield None since we don't need the db in peewee
db = connect_db(pdb, orm='peewee')
print(db, db.connection, db.connect_params)
if settings.db_reset:
db = connect_db(pdb, orm='peewee')
else:
async with asyncio.Lock():
db = connect_db(pdb, orm='peewee')

try:
yield db
finally:
if db and settings.db_reset:
print('closing')
db.close()


Expand Down

0 comments on commit 8fed729

Please sign in to comment.