File size: 1,012 Bytes
6e90909
 
 
bf179f1
dc53bbc
0ad866b
6e90909
 
 
dc53bbc
 
 
 
 
 
 
bf179f1
6e90909
44e6366
 
 
 
6e90909
 
 
720714e
6e90909
 
e18c05e
 
 
 
 
720714e
e18c05e
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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")