StreamingSSE / app_old.py
Pep1900's picture
Rename app.py to app_old.py
84d484b verified
Raw History Blame Contribute Delete
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=["*"],
)
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.post("/chat")
async def chat(request: Request):
data = await request.json()
app.state.last_msg = data.get("message", "")
return {"status": "ok"}
@app.get("/stream")
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")