[Python] How to send server-side events from python (fastapi) upon calls to a function that...

Discussão em 'Python' iniciado por Stack, Outubro 2, 2024.

  1. Stack

    Stack Membro Participativo

    I have the following problem: given a backend running fastapi, that has a streaming endpoint, which is used to update the frontend, I want to send these updates every time the function that updates the backend state gets called (which can be either by an scheduled job or a different endpoint that was hit and caused the state to be updated).

    A simplistic version of what I would like to implement would be:

    from fastapi import FastAPI
    from starlette.responses import StreamingResponse

    class State:
    def __init__(self):
    self.messages = []

    def update(self, new_messages):
    self.messages = new_messages
    # HERE: notify waiting stream endpoint

    app = FastAPI()

    state = State()

    @app.get('/stream')
    def stream():
    def event_stream():
    while True:
    # HERE lies the question: wait for state to be update
    for message in state.messages:
    yield 'data: {}\n\n'.format(json.dumps(message))
    return StreamingResponse(event_stream(), media_type="text/event-stream")


    And I would like this to keep running forever. Every time the state gets updated, the event_stream unblocks and send the messages.

    I have looked a threading and asyncio, but I have a feeling that I am missing some simple concept of how to do this in python.

    Continue reading...

Compartilhe esta Página