[Python] How to initialize a global object or variable and reuse it in every FastAPI endpoint?

Discussão em 'Python' iniciado por Stack, Fevereiro 22, 2025.

  1. Stack

    Stack Membro Participativo

    I am having a class to send notifications. When being initialized, it involves making a connection to a notification server, which is time-consuming. I use a background task in FastAPI to send notifications, as I don't want to delay the response due to notification. Below is the sample code.

    file1.py:
    noticlient = NotificationClient()

    @app.post("/{data}")
    def send_msg(somemsg: str, background_tasks: BackgroundTasks):
    result = add_some_tasks(data, background_tasks, noticlient)
    return result

    file2.py:
    def add_some_tasks(data, background_tasks: BackgroundTasks, noticlient):
    background_tasks.add_task(noticlient.send, param1, param2)
    result = some_operation
    return result


    Here, notification client is declared globally. I could have it initialized in file2.py under add_some_tasks, but it would get initialized every time a request arrives, and that would require some time. Is there any way to use a middleware to re-use it every time a request arrives, so that it doesn' t need to be initialized every time.

    or Approach two: Initialize notification in class def

    file1.py:
    class childFastApi(FastAPI):
    noticlient = NotificationClient()

    app = childFastApi()

    @app.post("/{data}")
    def send_msg(somemsg: str, background_tasks: BackgroundTasks):
    result = add_some_tasks(data, background_tasks, app.noticlient)
    return result

    Continue reading...

Compartilhe esta Página