Spaces:
Sleeping
Sleeping
File size: 3,544 Bytes
608b869 3f21436 608b869 c0402dc c226513 608b869 c226513 c0402dc c226513 3f21436 2bcdffa c226513 608b869 c0402dc c226513 608b869 a45aa1a 608b869 c0402dc c226513 608b869 c226513 2bcdffa 608b869 c0402dc 9870d3d c0402dc 608b869 2bcdffa 608b869 | 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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse, JSONResponse
from fastapi.middleware.cors import CORSMiddleware
import asyncio
import json
from typing import Dict, Set, List
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# Хранилище подключений: session_id -> set of queues
session_connections: Dict[str, Set[asyncio.Queue]] = {}
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.get("/sse")
async def sse(request: Request):
session_id = request.query_params.get("session_id")
if not session_id:
return JSONResponse(
{"error": "Необходимо указать session_id в параметрах запроса"},
status_code=400
)
queue = asyncio.Queue()
# Добавляем очередь в множество для данного session_id
if session_id not in session_connections:
session_connections[session_id] = set()
session_connections[session_id].add(queue)
async def event_stream():
try:
while True:
if await request.is_disconnected():
break
try:
data = await asyncio.wait_for(queue.get(), timeout=15)
# Имитация стриминга - разбиваем сообщение на части
message_parts = data.split() # Разбиваем по словам
for part in message_parts:
yield f"data: {part}\n\n"
await asyncio.sleep(0.5) # Пауза между частями
except asyncio.TimeoutError:
yield ": keepalive\n\n"
finally:
# Удаляем очередь при отключении
if session_id in session_connections:
session_connections[session_id].discard(queue)
if not session_connections[session_id]:
del session_connections[session_id]
return StreamingResponse(event_stream(), media_type="text/event-stream")
@app.post("/send")
async def send_message(request: Request):
try:
request_data = await request.json()
session_id = request_data.get("session_id")
if not session_id:
return JSONResponse(
{"error": "Необходимо указать session_id"},
status_code=400
)
messages = request_data.get("messages", [])
msg = messages[-1] if messages else "(empty)"
# Отправляем сообщение во все очереди для данного session_id
if session_id in session_connections:
data = json.dumps({
"messages": messages,
"last_message": msg
}, ensure_ascii=False)
# Отправляем во все активные подключения
for queue in session_connections[session_id]:
await queue.put(data)
return JSONResponse({
"status": "success",
"session_id": session_id,
"received_messages": messages
})
except json.JSONDecodeError:
return JSONResponse(
{"error": "Невалидный JSON в теле запроса"},
status_code=400
) |