Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python FastAPI依赖项(yield):如何手动调用它们?_Python_Fastapi_Starlette - Fatal编程技术网

Python FastAPI依赖项(yield):如何手动调用它们?

Python FastAPI依赖项(yield):如何手动调用它们?,python,fastapi,starlette,Python,Fastapi,Starlette,FastAPI使用Depends注入返回或产生的变量。例如: 附属国 def get_db: db=会话本地 尝试: 收益率分贝 最后: db.close ... def create_userdb:Session=Dependsget_db: ... 如果我想在FastAPI路由之外的其他地方使用get_db,我会怎么做?我知道这是Python的核心知识,但我似乎无法理解。我最初的想法是get_db的db=yield,但我不能在异步函数中调用yield,也不知道它是否还能工作。然后我试着: w

FastAPI使用Depends注入返回或产生的变量。例如:

附属国 def get_db: db=会话本地 尝试: 收益率分贝 最后: db.close ... def create_userdb:Session=Dependsget_db: ... 如果我想在FastAPI路由之外的其他地方使用get_db,我会怎么做?我知道这是Python的核心知识,但我似乎无法理解。我最初的想法是get_db的db=yield,但我不能在异步函数中调用yield,也不知道它是否还能工作。然后我试着:

with get_db() as db:
   pass
由于原始get_db未包装为@contextmanager,因此失败。注意,我不想修饰这个-我使用get_db作为示例,我需要处理更复杂的依赖项。最后,我尝试了db=nextget_db-这是可行的,但我认为这不是正确的解决方案。何时/如何最终被调用-何时我的方法返回?在其他一些依赖项中,有需要执行的生成后代码;我是否需要再次调用next以确保代码执行?似乎下一步不是正确的方法。有什么想法吗?

您可以将contextmanager用作返回上下文管理器的函数,而不是装饰器:

from contextlib import contextmanager

# Dependency
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# synchronously
with contextmanager(get_db)() as session:  # execute until yield. Session is yielded value
    pass
# execute finally on exit from with
但请记住,代码将同步执行。如果要在线程中执行,则可以使用FastAPI工具:

import asyncio
from contextlib import contextmanager

from fastapi.concurrency import contextmanager_in_threadpool


async def some_coro():
    async with contextmanager_in_threadpool(contextmanager(get_db)()) as session:
        pass
您可以将contextmanager用作返回上下文管理器的函数,而不是装饰器:

from contextlib import contextmanager

# Dependency
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# synchronously
with contextmanager(get_db)() as session:  # execute until yield. Session is yielded value
    pass
# execute finally on exit from with
但请记住,代码将同步执行。如果要在线程中执行,则可以使用FastAPI工具:

import asyncio
from contextlib import contextmanager

from fastapi.concurrency import contextmanager_in_threadpool


async def some_coro():
    async with contextmanager_in_threadpool(contextmanager(get_db)()) as session:
        pass

哎呀,我从来没想过——很高兴我问了!谢天谢地,我从来没想过——很高兴我问了!谢谢