1

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

Machine details:

  • Ubuntu 20
  • Python 3.8

Server:

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:

    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}')

After closing the client the SSE connection never close, instead it is stuck in the asyncio.sleep() command.

output from the server:

    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.
Marc Glisse
  • 7,550
  • 2
  • 30
  • 53
Mark
  • 11
  • 2

0 Answers0