[Python] How to use Background Tasks inside a function that is called by a FastAPI endpoint?

Discussão em 'Python' iniciado por Stack, Janeiro 25, 2025.

  1. Stack

    Stack Membro Participativo

    I have the below FastAPI endpoint:

    @app.post("/abcd", response_model=abcdResponseModel)
    async def getServerDetails(IncomingData: serverModel) -> abcdResponseModel:
    """
    Get Server Details
    """
    result = ServerDetails(IncomingData.dict())
    return result


    The above is calling the function below

    def ServerDetails(IncomingData: dict) -> Tuple[list, int]:
    background_tasks = BackgroundTasks()
    background_tasks.add(notification_func, arg1, arg2)
    response = some operation.....
    return response, 500


    Is this the way to do this, or do I need to create a BackgroundTasks() object inside getServerDetails endpoitn and pass it to the ServerDetails function?

    Continue reading...

Compartilhe esta Página