FastAPI 异步 class 依赖项
FastAPI async class dependencies
在 FastAPI 中,当标准函数用作依赖项时,它可以声明为常规 def
函数或异步 async def
函数。 FastAPI 声称在任何一种情况下它都会做正确的事情。
然而,以这种方式创建的依赖项不像 class 依赖项那样对自动完成友好。此外,class 依赖项具有更好的声明语法,您只需指定一次依赖项类型,FastAPI 就会确定您指的是哪种依赖项。
def read_item(常见:CommonQueryParam = Depends()):
但是 class 依赖项需要执行异步操作作为其初始化的一部分。是否可以一起使用 class 依赖项和异步。显然不能将 class __init__
函数声明为异步函数。还有其他方法可以让它发挥作用吗?
正如您正确注意到的那样,__init__
必须是同步的,您不能直接在其中调用 await
。但是您可以将所有异步代码作为子依赖项并将其作为 __init__
的输入。 FastAPI 将正确处理这种异步依赖。
样本:
async def async_dep():
await asyncio.sleep(0)
return 1
class CommonQueryParams:
def __init__(self, a: int = Depends(async_dep)):
self.a = a
在 FastAPI 中,当标准函数用作依赖项时,它可以声明为常规 def
函数或异步 async def
函数。 FastAPI 声称在任何一种情况下它都会做正确的事情。
然而,以这种方式创建的依赖项不像 class 依赖项那样对自动完成友好。此外,class 依赖项具有更好的声明语法,您只需指定一次依赖项类型,FastAPI 就会确定您指的是哪种依赖项。
def read_item(常见:CommonQueryParam = Depends()):
但是 class 依赖项需要执行异步操作作为其初始化的一部分。是否可以一起使用 class 依赖项和异步。显然不能将 class __init__
函数声明为异步函数。还有其他方法可以让它发挥作用吗?
正如您正确注意到的那样,__init__
必须是同步的,您不能直接在其中调用 await
。但是您可以将所有异步代码作为子依赖项并将其作为 __init__
的输入。 FastAPI 将正确处理这种异步依赖。
样本:
async def async_dep():
await asyncio.sleep(0)
return 1
class CommonQueryParams:
def __init__(self, a: int = Depends(async_dep)):
self.a = a