How to add my task to Background Tasks in FastAPI in non-decorator function

Viewed 38

In the FAST API Document the Background Tasks is running inside the router decorator function. I think this is DI ?

from fastapi import BackgroundTasks, FastAPI

app = FastAPI()


def write_notification(email: str, message=""):
    with open("log.txt", mode="w") as email_file:
        content = f"notification for {email}: {message}"
        email_file.write(content)


@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(write_notification, email, message="some notification")
    return {"message": "Notification sent in the background"}

And my question is...Is this possible to run it in a non-decorator function, some thing like

from fastapi import BackgroundTasks, FastAPI

app = FastAPI()


def write_notification(email: str, message=""):
    with open("log.txt", mode="w") as email_file:
        content = f"notification for {email}: {message}"
        email_file.write(content)

def some_function():
    background_tasks.add_task(write_notification, email, message="some notification")

@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
    some_function()
    return {"message": "Notification sent in the background"}

1 Answers

If you struggling with decorator, you can use code like this:

from fastapi import BackgroundTasks, FastAPI

app = FastAPI()


def write_notification(email: str, message=""):
    print('TASK RUNNING..')
    # with open("log.txt", mode="w") as email_file:
    #     content = f"notification for {email}: {message}"
    #     email_file.write(content)
    print('TASK DONE!')

def some_function(background_tasks: BackgroundTasks, email):
    background_tasks.add_task(write_notification, email, message="some notification")

@app.get("/send-notification/")
async def send_notification(email: str, background_tasks: BackgroundTasks):
    some_function(background_tasks, email)
    return {"message": "Notification sent in the background"} 

But i see no reason to create some_function(). What reason u to want to have some_function() ?

Related