From 498ea113e09d7781a79ca67078de6bbc13bdf2f6 Mon Sep 17 00:00:00 2001
From: zhaoqingang <zhaoqg0118@163.com>
Date: 星期二, 08 四月 2025 09:56:42 +0800
Subject: [PATCH] license同步任务

---
 app/service/basic.py |   73 +++++++++++++-----------------------
 1 files changed, 27 insertions(+), 46 deletions(-)

diff --git a/app/service/basic.py b/app/service/basic.py
index 9c22206..29bb02a 100644
--- a/app/service/basic.py
+++ b/app/service/basic.py
@@ -1,6 +1,7 @@
 import json
 
 import httpx
+import requests
 
 from Log import logger
 
@@ -12,7 +13,9 @@
     def _check_response(self, response: httpx.Response):
         """妫�鏌ュ搷搴斿苟澶勭悊閿欒"""
         if response.status_code not in [200, 201]:
-            raise Exception(f"Failed to fetch data from API: {response.text}")
+            # raise Exception(f"Failed to fetch data from API: {response.status_code}")
+            logger.error(f"Failed to fetch data from API:")
+            logger.error(response.status_code)
         response_data = response.json()
         return response_data
 
@@ -44,14 +47,11 @@
         url = f"{self.base_url}/exceltalk/download/excel"
         return await self.download_from_url(url, params={'excel_name': file_id})
 
-    async def excel_talk_upload(self, chat_id: str, filename: str, file_content: bytes):
+    async def excel_talk_upload(self, chat_id: str, files):
         url = f"{self.base_url}/exceltalk/upload/files"
         params = {'chat_id': chat_id, 'is_col': '0'}
 
-        # 鍒涘缓 FormData 瀵硅薄
-        files = [('files', (filename, file_content, 'application/octet-stream'))]
-
-        async with httpx.AsyncClient() as client:
+        async with httpx.AsyncClient(timeout=300) as client:
             response = await client.post(
                 url,
                 files=files,
@@ -64,28 +64,32 @@
         params = {'chat_id': chat_id}
         data = {"query": question}
         headers = {'Content-Type': 'application/json'}
-        buffer = bytearray()
-        async with httpx.AsyncClient(timeout=300.0) as client:
-            async with client.stream("POST", url, params=params, json=data, headers=headers) as response:
-                if response.status_code == 200:
+        with requests.post(url, headers=headers, json=data, params=params, timeout=60,
+                           stream=True) as response:
+            for line in response.iter_lines():
+                if line:
+                    decoded_line = line.decode("utf-8")
                     try:
-                        async for chunk in response.aiter_bytes():
-                            json_data = process_buffer(chunk, buffer)
-                            if json_data:
-                                yield json_data
-                                buffer.clear()
+                        if decoded_line.startswith("data:"):
+                            decoded_line = decoded_line[5:]
+                        answer = json.loads(decoded_line)
+                        answer["type"] = "message"
+                        yield answer
                     except GeneratorExit as e:
+                        logger.error("------------except GeneratorExit as e:---------------------")
+                        logger.error(e)
                         print(e)
                         yield {"message": "鍐呴儴閿欒", "type": "close"}
-                    finally:
-                        # 鍦ㄦ墍鏈夋暟鎹帴鏀跺畬姣曞悗璁板綍鏃ュ織
-                        logger.info("All messages received and processed - over")
-                        yield {"message": "", "type": "close"}
+                    # finally:
+                    #     # 鍦ㄦ墍鏈夋暟鎹帴鏀跺畬姣曞悗杩斿洖close
+                    #     yield {"message": "", "type": "close"}
 
                 else:
-                    yield f"Error: {response.status_code}"
-
-
+                    continue
+                    # yield f"Error: {response.status_code}"
+            else:
+            # 鍦ㄦ墍鏈夋暟鎹帴鏀跺畬姣曞悗杩斿洖close
+                yield {"message": "", "type": "close"}
 
     async def questions_talk(self, question, chat_id: str):
         logger.error("---------------questions_talk--------------------------")
@@ -103,27 +107,4 @@
 
     async def questions_talk_word_download(self, file_id: str):
         url = f"{self.base_url}/questions/download/word"
-        return await self.download_from_url(url, params={'excel_name': file_id})
-
-
-def process_buffer(data, buffer):
-    def try_parse_json(data1):
-        try:
-            return True, json.loads(data1)
-        except json.JSONDecodeError:
-            return False, None
-
-    if data.startswith(b'data:'):
-        # 鍒犻櫎 'data:' 澶�
-        data = data[5:].strip()
-    else:
-        pass
-
-    # 鐩存帴鎷兼帴鍒扮紦鍐插尯灏濊瘯瑙f瀽JSON
-    buffer.extend(data.strip())
-    success, parsed_data = try_parse_json(buffer)
-    if success:
-        return parsed_data
-    else:
-        # 瑙f瀽澶辫触锛岀户缁嫾鎺�
-        return None
+        return await self.download_from_url(url, params={'word_name': file_id})
\ No newline at end of file

--
Gitblit v1.8.0