fastapi中的Backgroundworker无法正常工作

问题描述 投票:0回答:1

我正在使用后台工作人员使用 FastApi 进行预测。一切似乎都正常,但如果我在另一个函数中扭曲后台工作函数并调用它,那么它就不起作用。为什么会发生这种情况?显然工作得当。我以这种方式传递函数,fastapi 中的后台工作人员是否无法工作?

# this is the working example
@app.get(api_names[0])
async def predict(background_tasks: BackgroundTasks,solute,solvent):
    background_tasks.add_task(predictions,solute,solvent)
    return {'success'}
# but when i change the above end point to below its not working
@app.get(api_names[0])
async def predict(background_tasks: BackgroundTasks,solute,solvent):
    sample = predict_dup(0)
    background_tasks.add_task(sample,solute,solvent)
    return {'success'}

async def predict_dup(task_id):
    if task_id == 0:
        return predictions
    elif task_id == 2:
        return predictions_two
python asynchronous fastapi background-task
1个回答
1
投票

根据文档

.add_task()
接收要在后台运行的任务函数,以及应传递给任务函数的任何参数。在您的情况下,从另一个函数返回函数以将其传递给后台任务的一种方法是使用
partial()
中的
functools
方法,该方法返回“一个新的部分对象,在调用时其行为将类似于功能”。因此,您可以按如下方式使用:

from functools import partial
return partial(predictions)
return partial(predictions_two)

或者,您可以使用一个字典来保存函数及其相应的任务 id,并使用它来根据给定 id 查找函数。下面的例子:

functions = {0: predictions, 1: predictions_two}
...
async def predict(background_tasks: BackgroundTasks,...
      background_tasks.add_task(functions[task_id], <ADD_FUNCTION_ARGUMENTS_HERE>)

请查看此答案,了解有关后台任务的更多详细信息。

© www.soinside.com 2019 - 2024. All rights reserved.