How to trigger a SSE With fastapi

Discussão em 'Angular' iniciado por רועי כחלון, Fevereiro 6, 2025.

  1. I have this code -

    event_queue = asyncio.Queue()
    @router.get("/stream")
    async def stream():
    async def event_generator():
    while True:
    try:
    event = await event_queue.get()
    yield f"data: {json.dumps(event)}\n\n"
    except asyncio.CancelledError:
    break

    return StreamingResponse(event_generator(), media_type="text/event-stream")


    and in my angular frontend, when the user generate an a image, I'm subscribing to stream. the way the image generation work - i'm waiting for a webhook with an image to get to my /webhook, and when its there I want to update my frontend user images (that's why i need sse).


    @router.post("/webhook")
    async def generate_status(request: Request, db: db_dependency):
    # unrelated login here
    await event_queue.put({"status": "uploaded"})
    return {"message": "Webhook processed and image uploaded"}


    so as you can see here I'm adding a event when its there. the problem is that its unstable, sometimes it works sometimes it doesnt, and I think that if multiple users use the same queue, it will bug out entirely..

    What is a good way to implement SSE from fastapi?

    I'm trying to get answers how to trigger events from a function, in fastapi - i didnt see anything that works about it online

    Continue reading...

Compartilhe esta Página