from fastapi import FastAPI, BackgroundTasks from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail app = FastAPI() @app.post("/email") async def send_email(background_tasks: BackgroundTasks, message: str): email = Mail( from_email="[email protected]", to_emails="[email protected]", subject="New message received!", html_content=message) background_tasks.add_task(send_email_task, email) def send_email_task(email: Mail): try: sg = SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY')) response = sg.send(email) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e)
from fastapi import FastAPI, BackgroundTasks from datetime import datetime app = FastAPI() @app.post("/process") async def process_data(background_tasks: BackgroundTasks, data: str): background_tasks.add_task(process_data_task, data) def process_data_task(data: str): # simulate long-running task for i in range(10): print(f"{datetime.now()} Processing data {data} - {i}")The code above defines an endpoint `/process` that accepts some data and adds a task to process the data in the background using a `process_data_task` function. The function prints a message every second for 10 seconds to simulate a long-running task. The package library used in the examples above is FastAPI itself, which provides the BackgroundTasks feature. However, other external packages are used as dependencies, such as `sendgrid` client for sending emails.