How can we use this package in multiple files
Hi my friend,
Could you please share the method to me? How can we share the database connection between multiple files. I organize my fastapi router in multiple files with APIRouter. In your package, it create a pool when fastapi project starts. How can we share this pool between multiple files?
Thanks
Hi! Any news yet on this?
I'm waiting as well.
~~maybe I misunderstood your question, but if you want to use the pool in a route you use the Dependency injection system of fastapi with either the connection or transaction method from this package...~~
after using the package myself I now understand your question :)
one solution is the following:
when initialising the app, store the db on the app.state
from fastapi import FastAPI
from fastapi import Depends
from fastapi_asyncpg import configure_asyncpg
app = FastAPI()
# we need to pass the fastapi app to make use of lifespan asgi events
app.state.db = configure_asyncpg(app, "postgresql://postgres:postgres@localhost/db")
now create your own two depends functions (similar to the ones in the init.py)
async def connection(request: Request):
async with app.state.db.pool.acquire() as db:
yield db
async def transaction(request: Request):
async with app.state.db.pool.acquire() as db:
txn = db.transaction()
await txn.start()
try:
yield db
except: # noqa
await txn.rollback()
raise
else:
await txn.commit()
you can now use the two depend functions like the ones mentioned in the README.md, with the slight differences that you can use them across multiple files...
in your main.py file
db = configure_asyncpg(app, f'''postgresql://{username}:{password}@{host}/{db_name}''')
in your router file use like this
router = APIRouter()
@router.post('/self/register')
async def register(req : Request ):
db = req.app.state.pool