简体   繁体   中英

FastAPI async class dependencies

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM