Упрощенная версия того, что я хотел бы реализовать, будет такой:< /p>
Код: Выделить всё
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")
Я просмотрел многопоточность и асинхронность, но у меня такое ощущение, что я отсутствует простое представление о том, как это сделать в Python.
Подробнее здесь: https://stackoverflow.com/questions/588 ... unction-th