简体   繁体   English

FastAPI 异步 class 依赖项

[英]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 中,当标准 function 用作依赖项时,它可以声明为常规def function 或异步async def function。 FastAPI claims that it will do the right thing in either case. FastAPI 声称它在任何一种情况下都会做正确的事情。

However dependencies created this way are not as friendly to autocomplete as class dependencies.但是,以这种方式创建的依赖项对自动完成的友好性不如 class 依赖项。 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.此外,class 依赖项具有更好的声明语法,只需指定一次依赖项的类型,FastAPI 就会找出您所指的依赖项。

def read_item(common: CommonQueryParam = Depends()): def read_item(common: CommonQueryParam = Depends()):

But of the class dependency needs to execute an async operation as a part of its initialization.但是 class 依赖项需要执行异步操作作为其初始化的一部分。 Is it possible to use class dependencies and async together.是否可以同时使用 class 依赖项和异步。 Clearly one cannot declare class __init__ function as async.显然,不能将 class __init__ function 声明为异步。 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.正如您正确注意到的那样, __init__必须是同步的,并且您不能直接在其中调用await But you can make all asynchronous code as sub-dependency and make it as input to the __init__ .但是您可以将所有异步代码作为子依赖项并将其作为__init__的输入。 FastAPI will handle this async dependency correctly. FastAPI 将正确处理此异步依赖项。

Sample:样本:

async def async_dep():
    await asyncio.sleep(0)
    return 1


class CommonQueryParams:
    def __init__(self, a: int = Depends(async_dep)):
        self.a = a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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