Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can we use this package in multiple files #4

Open
yiqgao opened this issue Jun 10, 2021 · 4 comments
Open

How can we use this package in multiple files #4

yiqgao opened this issue Jun 10, 2021 · 4 comments

Comments

@yiqgao
Copy link

yiqgao commented Jun 10, 2021

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

@fessacchiotto
Copy link

Hi! Any news yet on this?

@okay1204
Copy link

I'm waiting as well.

@jacksbox
Copy link

jacksbox commented Jan 24, 2022

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

@abhijitgujar86
Copy link

abhijitgujar86 commented Dec 15, 2022

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants