basic.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. import json
  2. import httpx
  3. import requests
  4. from Log import logger
  5. class BasicService:
  6. def __init__(self, base_url: str):
  7. self.base_url = base_url
  8. def _check_response(self, response: httpx.Response):
  9. """检查响应并处理错误"""
  10. if response.status_code not in [200, 201]:
  11. # raise Exception(f"Failed to fetch data from API: {response.status_code}")
  12. logger.error(f"Failed to fetch data from API:")
  13. logger.error(response.status_code)
  14. response_data = response.json()
  15. return response_data
  16. async def download_from_url(self, url, params=None):
  17. async with httpx.AsyncClient() as client:
  18. async with client.stream('GET', url, params=params) as response:
  19. if response.status_code == 200:
  20. # 获取文件名
  21. content_disposition = response.headers.get('Content-Disposition')
  22. if content_disposition:
  23. filename = content_disposition.split('filename=')[1].strip('"')
  24. else:
  25. filename = 'unknown_filename'
  26. # 获取内容类型
  27. content_type = response.headers.get('Content-Type')
  28. # 读取文件内容
  29. content = await response.aread()
  30. return content, filename, content_type
  31. else:
  32. raise Exception(f"Failed to download: {response.status_code}")
  33. async def excel_talk_image_download(self, file_id: str):
  34. url = f"{self.base_url}/exceltalk/download/image"
  35. return await self.download_from_url(url, params={'images_name': file_id})
  36. async def excel_talk_excel_download(self, file_id: str):
  37. url = f"{self.base_url}/exceltalk/download/excel"
  38. return await self.download_from_url(url, params={'excel_name': file_id})
  39. async def excel_talk_upload(self, chat_id: str, files):
  40. url = f"{self.base_url}/exceltalk/upload/files"
  41. params = {'chat_id': chat_id, 'is_col': '0'}
  42. async with httpx.AsyncClient(timeout=300) as client:
  43. response = await client.post(
  44. url,
  45. files=files,
  46. params=params
  47. )
  48. return self._check_response(response)
  49. async def excel_talk(self, question: str, chat_id: str):
  50. url = f"{self.base_url}/exceltalk/talk"
  51. params = {'chat_id': chat_id}
  52. data = {"query": question}
  53. headers = {'Content-Type': 'application/json'}
  54. with requests.post(url, headers=headers, json=data, params=params, timeout=60,
  55. stream=True) as response:
  56. for line in response.iter_lines():
  57. if line:
  58. decoded_line = line.decode("utf-8")
  59. try:
  60. if decoded_line.startswith("data:"):
  61. decoded_line = decoded_line[5:]
  62. answer = json.loads(decoded_line)
  63. answer["type"] = "message"
  64. yield answer
  65. except GeneratorExit as e:
  66. logger.error("------------except GeneratorExit as e:---------------------")
  67. logger.error(e)
  68. print(e)
  69. yield {"message": "内部错误", "type": "close"}
  70. # finally:
  71. # # 在所有数据接收完毕后返回close
  72. # yield {"message": "", "type": "close"}
  73. else:
  74. continue
  75. # yield f"Error: {response.status_code}"
  76. else:
  77. # 在所有数据接收完毕后返回close
  78. yield {"message": "", "type": "close"}
  79. async def questions_talk(self, question, chat_id: str):
  80. logger.error("---------------questions_talk--------------------------")
  81. url = f"{self.base_url}/questions/talk"
  82. params = {'chat_id': chat_id}
  83. headers = {'Content-Type': 'text/plain'}
  84. async with httpx.AsyncClient(timeout=1800) as client:
  85. response = await client.post(
  86. url,
  87. data=question,
  88. headers=headers,
  89. params=params
  90. )
  91. return self._check_response(response)
  92. async def questions_talk_word_download(self, file_id: str):
  93. url = f"{self.base_url}/questions/download/word"
  94. return await self.download_from_url(url, params={'word_name': file_id})