fastapi_asyncpg icon indicating copy to clipboard operation
fastapi_asyncpg copied to clipboard

How can we use this package in multiple files

Open yiqgao opened this issue 4 years ago • 4 comments

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

yiqgao avatar Jun 10 '21 08:06 yiqgao

Hi! Any news yet on this?

fessacchiotto avatar Sep 13 '21 03:09 fessacchiotto

I'm waiting as well.

okay1204 avatar Sep 16 '21 23:09 okay1204

~~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...

jacksbox avatar Jan 24 '22 14:01 jacksbox

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

abhijitgujar86 avatar Dec 15 '22 18:12 abhijitgujar86