2

The documentation explains how to send background tasks from controllers, like

@app.get("/mypath")
async def send_notification(email: str, background_tasks: BackgroundTasks): 
    pass

I wonder if there's a way to emit a background task out of controller scope (I mean, without needing to pass the BackgroundTasks object from controller to over all my function calls)

I did try this but didn't work

from fastapi import BackgroundTasks
def print_key(key: str):
    print(f"test bg task: {key}")

def send_stats(key: str):
    BackgroundTasks().add_task(print_key, key)
Carlos Rojas
  • 334
  • 5
  • 13

1 Answers1

0

Try to create an instance of the BackgroundTasks class at the application level instead, and then use it in your function.

from fastapi import BackgroundTasks, FastAPI

app = FastAPI()
background_tasks = BackgroundTasks()

def print_key(key: str):
    print(f"test bg task: {key}")

def send_stats(key: str):
    background_tasks.add_task(print_key, key)

@app.get("/mypath")
async def my_path(email: str):
    send_stats("some_key")
    return {"message": "Task added to background tasks"}
Anton Petrov
  • 315
  • 1
  • 3
  • 12