Replies: 4 comments 1 reply
-
That whole bottom section in the documentation is quite confusing, because while FastAPI does use In the docs
should really read:
and in fact I would argue that whole section is unnecessary and only leads to confusion. In your specific case, to eliminate the duplicate code you can do:
then continue to use A separate issue is that the pattern of
means you're opening context managers and wrapping them up in the context manager under the hood of the dependency system. |
Beta Was this translation helpful? Give feedback.
-
I would agree with you that the documentation is confusing, but this clears things up with a nice simple solution, thanks! |
Beta Was this translation helpful? Give feedback.
-
This helped me out, thanks all. Here's what mine looks like: async def database_session():
"""
Returns a database Session for use with fastapi Depends()
"""
session = async_scoped_session(_db_session, scopefunc=current_task)
try:
yield session
finally:
await session.remove() @app.on_event("startup")
async def create_admin_user():
"""
Makes sure the app's admin user exists on startup
"""
DatabaseSession = asynccontextmanager(database_session)
async with DatabaseSession() as session:
do_db_stuff_with_db_session(session) @router.get("/")
async def get_user(user_id: str, session: AsyncSession = Depends(database_session)):
do_stuff_with_db_session(session) |
Beta Was this translation helpful? Give feedback.
-
I don't know why this is not allowed... Maybe I'm missing something? But I guess either a PR allowing that or a PR improving the docs should be created 🤔 |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
First check
Description
I have a database pool with which I have to define two exact method except for the
@asynccontextmanager
decorator.One is used in my internal code:
And the other with the
Depends
:In the documentation there is a line which states
If you try:
I actually get an
AttributeError
. I'm assumingpool
is yieled instead ofpool.__call__
.Which makes it pretty clear that I cannot use a contextmanager in a
Depends
, but this creates duplicate and non consistent code when getting a db connection.Is this the way it is? Can
Depends
work with both regular yields and contextmanagers directly?Beta Was this translation helpful? Give feedback.
All reactions