Spaces:
Sleeping
Sleeping
Download app_old.py from Pep1900/StreamingSSE: direct link, hf CLI and curl.
- Browser
- Download file 1.01 kB
-
https://huggingface.co/spaces/Pep1900/StreamingSSE/resolve/main/app_old.py
- Command line
-
hf download hf://spaces/Pep1900/StreamingSSE/app_old.py
-
curl -L -o app_old.py https://huggingface.co/spaces/Pep1900/StreamingSSE/resolve/main/app_old.py
1.01 kB
| from fastapi import FastAPI, Request | |
| from fastapi.responses import StreamingResponse | |
| from time import sleep | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.middleware.cors import CORSMiddleware | |
| import asyncio | |
| app = FastAPI() | |
| app.state.last_msg = "" | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], # или укажи домен фронта | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| async def root(): | |
| return {"message": "Hello World"} | |
| async def chat(request: Request): | |
| data = await request.json() | |
| app.state.last_msg = data.get("message", "") | |
| return {"status": "ok"} | |
| async def stream(): | |
| async def event_gen(): | |
| for ch in app.state.last_msg: | |
| yield f"data: {ch}\n\n" | |
| await asyncio.sleep(0.3) # обязательно await | |
| yield "data: [END]\n\n" | |
| return StreamingResponse(event_gen(), media_type="text/event-stream") | |