Reputation: 9481
In FastAPI when a standard function is used as a dependency it could be used declared as regular def
function or an asynchronous async def
function. FastAPI claims that it will do the right thing in either case.
However dependencies created this way are not as friendly to autocomplete as class dependencies. Also class dependencies have a bit better declaration syntax one can just specify the type of dependency once and FastAPI will figure out which dependency you mean.
def read_item(common: CommonQueryParam = Depends()):
But of the class dependency needs to execute an async operation as a part of its initialization. Is it possible to use class dependencies and async together. Clearly one cannot declare class __init__
function as async. Is there another way to make it work?
Upvotes: 5
Views: 6457
Reputation: 32133
As you rightly noticed, __init__
has to be synchronous, and you cannot straightforwardly call await
inside it. But you can make all asynchronous code as sub-dependency and make it as input to the __init__
. FastAPI will handle this async dependency correctly.
Sample:
async def async_dep():
await asyncio.sleep(0)
return 1
class CommonQueryParams:
def __init__(self, a: int = Depends(async_dep)):
self.a = a
Upvotes: 9