sysid / sse-starlette

BSD 3-Clause "New" or "Revised" License
504 stars 35 forks source link

Async behavior will turn to blocking behavior while working with GzipMiddleWare #84

Closed doglex closed 7 months ago

doglex commented 7 months ago

Workaround is sub application

doglex commented 7 months ago

demo

# main.py
app = FastAPI()
from sse import route as subapp
app.mount("/sse", subapp)
app1 = FastAPI()
app1.add_middleware(GZipMiddleware, minimum_size=1000)
app1.include_router(be.route, prefix="/be")
app.mount("/", app1)
# sse.py
from fastapi import APIRouter, Request, FastAPI
import asyncio
from sse_starlette.sse import EventSourceResponse
route = FastAPI()
@route.get("/s1")
async def message_stream(req: Request):
    async def event_publisher():
        i = 50
        try:
          while i:
              i -= 1
              # print(i)
              yield dict(data=i)
              await asyncio.sleep(0.5)
        except asyncio.CancelledError as e:
          print(f"Disconnected from client (via refresh/close) {req.client}")
          # Do any other cleanup, if any
          raise e
    return EventSourceResponse(event_publisher())
sysid commented 7 months ago

@doglex, I am not sure whether I understand what you are trying to point out.

README states: Caveat: SSE streaming does not work in combination with https://github.com/encode/starlette/issues/20#issuecomment-704106436.

Do you propose a solution/workaround for this?

doglex commented 7 months ago

Caveat

Yes, it is the issue

sysid commented 7 months ago

If you have got a solution please open a PR. Would be much appreciated