在FastAPI中,我试图理解为什么后台实例没有在路由函数处理程序外部创建,以及它的不同行为.

Examples:

标准文档示例按预期工作:

@app.get('/')
async def index(background_tasks: BackgroundTasks):
    background_tasks.add_task(some_function_reference)
    #Executes non-blocking in the same asyncio loop without any issues
    return "Hello"

在路由函数之外添加BACKGROUND_TASKS时,它的行为有所不同:

async def some_logic(background_tasks: BackgroundTasks):
    #Throws a "required positional argument missing" error
    background_tasks.add_task(some_function_reference)


@app.get('/')
async def index():
    await some_logic()
    #Executes non-blocking in the same asyncio loop
    return "Hello"

同时,如果我们try 在some_logic函数中初始化BackgroundTasks,则任务不会按如下方式运行:

async def some_logic():
    #Does not Run
    background_tasks = BackgroundTasks()
    background_tasks.add_task(some_function_reference)


@app.get('/')
async def index(background_tasks: BackgroundTasks):
    await some_logic()
    #Executes non-blocking in the same asyncio loop
    return "Hello"

为什么这三个 case 会有所不同?为什么我需要将后台任务从路由函数传递到下面调用的函数?

推荐答案

BackgroundTasks个实例由FastAPI框架填充并注入调用方.在第一个示例中,您使用的路由具有由FastAPI注入的依赖项.

在第二个示例中,您将调用some_logic作为常规函数.因为它不是由FastAPI直接调用的,所以没有发生依赖注入.

在第三个示例中,您创建了一个新的后台任务实例,但这是一个与FastAPI关心的实例不同的实例.您可以在其中创建任务,但没有注册处理程序来对其执行操作.

在这种情况下,如果目标是使后台任务更容易应用于方法,则可以添加some_logic函数作为路径的依赖项.依赖项由FastAPI调用,因此参数将被注入.

示例:

from fastapi import FastAPI, Depends
from starlette.background import BackgroundTasks
from starlette.testclient import TestClient

app = FastAPI()


def task():
    print("Hello from the Background!")


async def some_logic(background_tasks: BackgroundTasks):
    background_tasks.add_task(task)


@app.get('/', dependencies=[Depends(some_logic)])
async def index():
    return "Hello"


with TestClient(app) as client:
    client.get("/")
Hello from the Background!

Python相关问答推荐

如何在WTForm中使用back_plumates参考brand_id?

X射线扫描显示Docker中的pip漏洞,尽管图像中未安装pip

根据多列和一些条件创建新列

使用imap-tools时错误,其邮箱地址包含域名中的非默认字符

强制venv在bin而不是收件箱文件夹中创建虚拟环境

如何销毁框架并使其在tkinter中看起来像以前的样子?

如何使用stride_tricks.as_strided逆转NumPy数组

仅从风格中获取 colored颜色 循环

如何才能知道Python中2列表中的巧合.顺序很重要,但当1个失败时,其余的不应该失败或是0巧合

Odoo 14 hr. emergency.public内的二进制字段

Pandas 滚动最接近的价值

通过Selenium从页面获取所有H2元素

Excel图表-使用openpyxl更改水平轴与Y轴相交的位置(Python)

在Python中管理打开对话框

NP.round解算数据后NP.unique

在np数组上实现无重叠的二维滑动窗口

当我try 在django中更新模型时,模型表单数据不可见

Python导入某些库时非法指令(核心转储)(beautifulsoup4."" yfinance)

为什么Django管理页面和我的页面的其他CSS文件和图片都找不到?'

网格基于1.Y轴与2.x轴显示在matplotlib中