Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background Task in FastAPI is not working properly

I am performing predictions with FastAPI, using background tasks. Everything seems to be working, but if I warp the background task function in another function and call it then it's not working. Why is this happening? Don't background tasks in FastAPI work when i 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>)

Please have a look at this answer for more details on Background Tasks.

like image 157
Chris Avatar answered May 31 '26 06:05

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!