sysid / sse-starlette

BSD 3-Clause "New" or "Revised" License
545 stars 37 forks source link

sse-starlette generator getting stuck after closing the sse client #40

Closed markFir1 closed 2 years ago

markFir1 commented 2 years ago

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

Machine details:

Related Packages:

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 2 years ago

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