-
First Check
Commit to Help
Example Codeimport asyncio
import uvicorn
from fastapi import FastAPI, Request
from sse_starlette.sse import EventSourceResponse
from demo.fastapi_sse import main
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
STREAM_DELAY = 1 # second
RETRY_TIMEOUT = 15000 # milisecond
@app.get('/stream')
async def message_stream(request: Request):
def new_messages():
# Add logic here to check for new messages
yield 'Hello World'
async def event_generator():
while True:
# If client closes connection, stop sending events
if await request.is_disconnected():
print("The web client connection has been disconnected")
break
# Checks for new messages and return them to client if any
if new_messages():
yield {
"event": "new_message",
"id": "message_id",
"retry": RETRY_TIMEOUT,
"data": "message_content"
}
await asyncio.sleep(STREAM_DELAY)
return EventSourceResponse(event_generator())
if __name__ == "__main__":
# uvicorn.run("demo.fastapi.main:app",host="0.0.0.0", port=9000, reload=False)
import asyncio
import uvloop
from hypercorn.asyncio import serve
from hypercorn.config import Config
config = Config()
config.bind = [f"0.0.0.0:9000"]
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(serve(main.app, config))DescriptionI read this article: To monitor whether the client is disconnected, but this code does not take effect in reality. Operating SystemLinux Operating System DetailsNo response FastAPI Version0.91.0 Python VersionPython 3.11.2 Additional ContextI read the fastapi documentation, and the documentation only describes that websocket is clearly able to get the client disconnection event by the server, but here I want to know why this function is used when using EventSourceResponse The mechanism for judging disconnection has not taken effect, and how to solve it? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
Sorry, I found this module is not fastapi official project |
Beta Was this translation helpful? Give feedback.
Sorry, I found this module is not fastapi official project