aliyun.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on 2024-02-26
  4. ---------
  5. @summary: oss附件服务
  6. ---------
  7. """
  8. from functools import partial
  9. from io import BytesIO
  10. import requests
  11. JY_OSS_URL = "http://172.17.162.27:18011"
  12. JY_OSS_TEST_URL = "http://172.31.31.203:1111"
  13. class AttachmentError(Exception):
  14. def __init__(self, *args, **kwargs):
  15. if 'code' not in kwargs and 'reason' not in kwargs:
  16. kwargs['code'] = 0
  17. kwargs['reason'] = '附件错误'
  18. if 'reason' in kwargs and kwargs['reason'] is None:
  19. kwargs['reason'] = '附件错误'
  20. for key, val in kwargs.items():
  21. setattr(self, key, val)
  22. super(AttachmentError, self).__init__(*args, kwargs)
  23. class OssClient(object):
  24. def __init__(self, domain: str):
  25. # 初始化函数,用于创建类的实例
  26. self.domain = domain
  27. def upload(self, args: dict) -> dict:
  28. reply = {"error_code": -1}
  29. try:
  30. files = {
  31. 'file': (args['object_name'], BytesIO(args['stream'])),
  32. }
  33. data = {
  34. 'bucket_id': args['bucket_id'],
  35. 'object_name': args['object_name'],
  36. 'gzip': args.get('gzip', False),
  37. }
  38. response = requests.post(
  39. f"{self.domain}/ossservice/upload",
  40. files=files,
  41. data=data,
  42. timeout=300,
  43. )
  44. if response.status_code == 200:
  45. reply.update(response.json())
  46. else:
  47. reply['error_msg'] = f"HTTP error: {response.status_code}"
  48. except Exception as e:
  49. reply['error_msg'] = str(e)
  50. return reply
  51. def download(self, args: dict):
  52. reply = {}
  53. try:
  54. data = {
  55. "bucket_id": args["bucket_id"],
  56. "object_name": args["object_name"]
  57. }
  58. url = f"{self.domain}/ossservice/download"
  59. response = requests.post(url, data=data, timeout=300)
  60. response.raise_for_status()
  61. reply["error_code"] = 0
  62. reply["error_msg"] = "下载成功"
  63. reply["data"] = response.content
  64. except Exception as e:
  65. reply["error_code"] = -1
  66. reply["error_msg"] = str(e)
  67. return reply
  68. def delete(self, args: dict):
  69. reply = {}
  70. try:
  71. data = {
  72. "bucket_id": args["bucket_id"],
  73. "object_name": args["object_name"]
  74. }
  75. url = f"{self.domain}/ossservice/delete"
  76. response = requests.post(url, data=data, timeout=10)
  77. response.raise_for_status()
  78. reply = response.json()
  79. reply["error_code"] = 0
  80. except Exception as e:
  81. reply["error_code"] = -1
  82. reply["error_msg"] = str(e)
  83. return reply
  84. class JyOssClient:
  85. def __init__(self, domain=None, mode="test"):
  86. if domain is None:
  87. domain = JY_OSS_URL
  88. if mode == "test":
  89. domain = JY_OSS_TEST_URL
  90. self._oss_client = OssClient(domain=domain)
  91. def upload(self, bucket_id, object_name, stream, gzip=False, retries=3, err_show=True):
  92. """
  93. 上传附件
  94. :param str bucket_id: 文件名
  95. :param str object_name: 对象名称
  96. :param bytes stream: 文件流
  97. :param bool gzip: 是否压缩
  98. :param int retries: 上传最大重试次数
  99. :param bool err_show: 是否展示错误
  100. """
  101. args = {
  102. "bucket_id": bucket_id,
  103. "object_name": object_name,
  104. "gzip": gzip,
  105. "stream": stream
  106. }
  107. ret = {"error_msg": "附件上传错误", "error_code": -1}
  108. for _ in range(retries):
  109. ret = self._oss_client.upload(args)
  110. if ret["error_code"] == 0:
  111. return ret
  112. if err_show:
  113. raise AttachmentError(reason=ret.get("error_msg") or "附件上传错误")
  114. return ret
  115. def download(self, bucket_id, object_name, retries=3, err_show=False):
  116. """
  117. 下载附件
  118. :param str bucket_id: 文件名
  119. :param str object_name: 对象名称
  120. :param int retries: 下载最大重试次数
  121. :param bool err_show: 是否展示错误
  122. """
  123. args = {
  124. "bucket_id": bucket_id,
  125. "object_name": object_name,
  126. }
  127. ret = {"error_msg": "附件下载失败", "error_code": -1}
  128. for _ in range(retries):
  129. ret = self._oss_client.download(args)
  130. if ret["error_code"] == 0 or ret["error_code"] == -1:
  131. return ret
  132. if err_show:
  133. raise AttachmentError(reason=ret.get("error_msg") or "附件下载失败")
  134. return ret
  135. def delete(self, bucket_id, object_name, retries=3, err_show=False):
  136. """
  137. 删除附件
  138. :param str bucket_id: 文件名
  139. :param str object_name: 对象名称
  140. :param int retries: 删除最大重试次数
  141. :param bool err_show: 是否展示错误
  142. """
  143. args = {
  144. "bucket_id": bucket_id,
  145. "object_name": object_name,
  146. }
  147. ret = {"error_msg": "附件删除失败", "error_code": -1}
  148. for _ in range(retries):
  149. ret = self._oss_client.delete(args)
  150. if ret["error_code"] == 0:
  151. return ret
  152. if err_show:
  153. raise AttachmentError(reason=ret.get("error_msg") or "附件删除失败")
  154. return ret
  155. _upload = partial(upload, "file")
  156. push_oss_from_local = push_oss_from_stream = _upload
  157. AliYunService = JyOssClient