From a1b7795af6095cd821a3bc279ec2fcc9a03b3b98 Mon Sep 17 00:00:00 2001 From: zhangqian <zhangqian@123.com> Date: 星期二, 29 十月 2024 21:30:22 +0800 Subject: [PATCH] 代码优化 --- app/api/report.py | 31 +++++++++++++++++++------------ 1 files changed, 19 insertions(+), 12 deletions(-) diff --git a/app/api/report.py b/app/api/report.py index 1bc08dc..254695d 100644 --- a/app/api/report.py +++ b/app/api/report.py @@ -65,8 +65,8 @@ files = data.get("files", []) steps = data.get("intermediate_steps", "") msg = data.get("message", "") + if len(files) != 0 or (steps and last_message == "step") or msg or data["type"] == "close": - last_message = "step" if steps else "message" if data["type"] == "close": t = "close" else: @@ -76,23 +76,30 @@ await websocket.send_json(result) print(f"Forwarded to client, {chat_id}: {result}") + last_message = "step" if steps else "message" + # 鍚姩涓や釜浠诲姟锛屽垎鍒鐞嗗鎴风鍜屾湇鍔$鐨勬秷鎭� tasks = [ asyncio.create_task(forward_to_service()), asyncio.create_task(forward_to_client()) ] - done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) - # 鍙栨秷鏈畬鎴愮殑浠诲姟 - for task in pending: - task.cancel() - try: - await task - except asyncio.CancelledError: - pass - - except WebSocketDisconnect: - print(f"Client {chat_id} disconnected") + except WebSocketDisconnect as e: + print(f"WebSocket connection closed with code {e.code}: {e.reason}") + await websocket.close() + await service_websocket.close() + except Exception as e: + print(f"Exception occurred: {e}") + finally: + print("Cleaning up resources") + # 鍙栨秷鎵�鏈変换鍔� + for task in tasks: + if not task.done(): + task.cancel() + try: + await task + except asyncio.CancelledError: + pass @router.get("/variables/list", response_model=ResponseList) -- Gitblit v1.8.0