sysid/sse-starlette

sse-starlette generator getting stuck after closing the sse client

markFir1 opened this issue · 1 comments

I am trying to use SSE as fastApi endpoint. And the event generator never exits and gets stuck.

Machine details:

  • Ubuntu 20
  • Python 3.8

Related Packages:

  • fastapi==0.67.0
  • sse-starlette==0.6.2
  • uvicorn==0.13.3

Server code:

import asyncio
import uvicorn
from fastapi import FastAPI, Request
from sse_starlette.sse import EventSourceResponse
from concurrent.futures import CancelledError


app = FastAPI()


@app.get("/")
async def get_events_stream(request: Request):

    async def event_generator():
        count = 0
        print("starting the loop")
        while True:
            try:
                print(f"Sleeping - {count}")
                await asyncio.sleep(1)
                print("Finished sleeping")
            except CancelledError:
                if not await request.is_disconnected():
                    print('Cancelled future error')
            except Exception:
                print('Exception!')

            if await request.is_disconnected():
                print("disconnected")
                break

            yield {'event': 'message', 'data': count}
            count += 1
        print("ended the loop - finished serving")

    return EventSourceResponse(event_generator(), ping=1)


uvicorn.run(app=app, port=5555, loop="asyncio")

Client (It is possible to just go to browser http://localhost:5555) :

from sseclient import SSEClient

address = "http://127.0.0.1:5555/"


read_client = SSEClient(address)

for new_event in read_client:
    print(f'event: {new_event.event}, {new_event.data}')

Output:

INFO:     Started server process [15989]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:5555 (Press CTRL+C to quit)
INFO:     127.0.0.1:51114 - "GET / HTTP/1.1" 200 OK
starting the loop
Sleeping - 0
Finished sleeping
Sleeping - 1
Finished sleeping
Sleeping - 2
Finished sleeping
Sleeping - 3
Finished sleeping
Sleeping - 4  # The client stopped.
sysid commented

@markFir1, cannot reproduce your problem. Your code example is working for me.