Initial upload for secondary development
This commit is contained in:
40
chatlog_fastAPI/routers/sse.py
Normal file
40
chatlog_fastAPI/routers/sse.py
Normal file
@@ -0,0 +1,40 @@
|
||||
import asyncio, json, logging
|
||||
from fastapi import APIRouter, Query
|
||||
from fastapi.responses import StreamingResponse
|
||||
from services.chatlog_client import chatlog_client
|
||||
from services.message_formatter import attach_quote
|
||||
|
||||
router = APIRouter(prefix="/api/sse", tags=["sse"])
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@router.get("/chatlog")
|
||||
async def sse_chatlog(talker: str = Query(...)):
|
||||
async def generate():
|
||||
try:
|
||||
data = await chatlog_client.get_messages(talker, limit=1, offset=0)
|
||||
last_total = data.get("total", 0)
|
||||
except Exception:
|
||||
last_total = 0
|
||||
|
||||
while True:
|
||||
await asyncio.sleep(2)
|
||||
try:
|
||||
data = await chatlog_client.get_messages(talker, limit=50, offset=last_total)
|
||||
msgs = data.get("messages") or data.get("items") or []
|
||||
new_total = data.get("total", last_total)
|
||||
for msg in msgs:
|
||||
attach_quote(msg)
|
||||
yield f"data: {json.dumps(msg, ensure_ascii=False)}\n\n"
|
||||
if new_total > last_total:
|
||||
last_total = new_total
|
||||
except asyncio.CancelledError:
|
||||
return
|
||||
except Exception as e:
|
||||
log.warning(f"[sse] poll error: {e}")
|
||||
|
||||
return StreamingResponse(
|
||||
generate(),
|
||||
media_type="text/event-stream",
|
||||
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
|
||||
)
|
||||
Reference in New Issue
Block a user