Backgroundworker in fastapi is not working properly

Viewed 371

I am doing predictions with FastApi using background workers. Everything seems working but if I warp the background worker function in another function and call it then it's not working. Why does this is happening? It is obvious to work right. Do background workers in fastapi won't work i do pass the function this way?

# 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
1 Answers

As per the documentation, .add_task(), receives a task function to be run in the background, along with any arguments that should be passed to the task function. In your case, one way to return a function from another function to pass it to the background tasks would be to use the partial() method from functools that returns "a new partial object which when called will behave like func". Hence, you could use as follows:

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

Alternatively, you could have a dictionary that keeps the functions with their corresponding task ids, and use it to look up for a function based on a given id. Example below:

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