aliyun.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. import hashlib
  2. import os
  3. import traceback
  4. import oss2
  5. import requests
  6. from feapder import setting
  7. import time
  8. class UploadOSS:
  9. """阿里云 oss"""
  10. def __init__(self):
  11. oss_conf = setting.oss_
  12. self.file_path: str = ""
  13. self.file_stream: bytes = b''
  14. self.__acc_key_id = oss_conf['key_id']
  15. self.__acc_key_secret = oss_conf['key_secret']
  16. self.__endpoint = oss_conf['endpoint']
  17. self.__bucket_name = oss_conf['bucket_name']
  18. @property
  19. def fid(self):
  20. """
  21. 文本摘要值
  22. @return: 十六进制摘要值
  23. """
  24. sha1 = hashlib.sha1()
  25. sha1.update(str(self.file_stream).encode("utf-8"))
  26. return sha1.hexdigest()
  27. @property
  28. def file_size(self):
  29. """
  30. 文件的大小,将字节(bytes)转化(kb/M/G单位)
  31. @return: 文件大小
  32. """
  33. try:
  34. size = os.path.getsize(self.file_path)
  35. except Exception:
  36. traceback.print_exc()
  37. else:
  38. try:
  39. _kb = float(size) / 1024
  40. except:
  41. return "Error"
  42. else:
  43. if _kb >= 1024:
  44. _M = _kb / 1024
  45. if _M >= 1024:
  46. _G = _M / 1024
  47. return "{:.1f} G".format(_G)
  48. else:
  49. return "{:.1f} M".format(_M)
  50. else:
  51. return "{:.1f} kb".format(_kb)
  52. def get_state(self, attachment, **kwargs):
  53. """
  54. 下载附件并上传阿里oss
  55. @param attachment: 附件
  56. @return: 附件处理结果
  57. """
  58. request_params = {
  59. 'headers': setting.headers,
  60. 'timeout': 20,
  61. 'stream': True,
  62. **kwargs
  63. }
  64. with requests.get(attachment["org_url"], **request_params) as req:
  65. if req.status_code == 200:
  66. self.file_stream = req.content
  67. # img_dir = "file"
  68. img_dir = f"file/{attachment['channel']}"
  69. # 文件夹不存在则创建文件夹
  70. if not os.path.exists(img_dir):
  71. os.makedirs(img_dir, mode=0o777, exist_ok=True)
  72. # 打开目录,放入下载的附件
  73. self.file_path = "{}/{}".format(img_dir, attachment["filename"])
  74. with open(self.file_path, 'wb') as f:
  75. f.write(self.file_stream)
  76. # 上传附件
  77. self.put_oss_from_local()
  78. file_state = self.file_state(attachment)
  79. # 删除附件
  80. os.remove(self.file_path)
  81. # 返回附件上传处理信息
  82. return file_state
  83. else:
  84. attachment["ftype"] = str(attachment["filename"]).split(".")[1]
  85. attachment["url"] = 'oss'
  86. attachment["fid"] = self.fid + "." + attachment["ftype"]
  87. attachment["size"] = '0kb'
  88. attachment["false"] = True
  89. return attachment
  90. def post_state(self, attachment, **kwargs):
  91. """
  92. 下载附件并上传阿里oss
  93. @param attachment: 附件
  94. @return: 附件处理结果
  95. """
  96. request_params = {
  97. 'headers': setting.headers,
  98. 'timeout': 20,
  99. 'stream': True,
  100. **kwargs
  101. }
  102. with requests.post(attachment["org_url"], **request_params) as req:
  103. if req.status_code == 200:
  104. self.file_stream = req.content
  105. img_dir = f"file/{attachment['channel']}"
  106. # 文件夹不存在则创建文件夹
  107. if not os.path.exists(img_dir):
  108. os.makedirs(img_dir, mode=0o777, exist_ok=True)
  109. # 打开目录,放入下载的附件
  110. self.file_path = "{}/{}{}".format(img_dir,time.time(),attachment["filename"])
  111. with open(self.file_path, 'wb') as f:
  112. f.write(self.file_stream)
  113. # 上传附件
  114. self.put_oss_from_local()
  115. file_state = self.file_state(attachment)
  116. # 删除附件
  117. # os.remove(self.file_path)
  118. # 返回附件上传处理信息
  119. return file_state
  120. else:
  121. attachment["ftype"] = str(attachment["filename"]).split(".")[1]
  122. attachment["url"] = 'oss'
  123. attachment["fid"] = self.fid + "." + attachment["ftype"]
  124. attachment["size"] = '0kb'
  125. attachment["false"] = True
  126. return attachment
  127. def put_oss_from_local(self):
  128. """上传一个本地文件到阿里OSS的普通文件"""
  129. auth = oss2.Auth(self.__acc_key_id, self.__acc_key_secret)
  130. bucket = oss2.Bucket(auth, self.__endpoint, self.__bucket_name)
  131. bucket.put_object_from_file(self.fid, self.file_path)
  132. def file_state(self, attachment):
  133. """
  134. 文件信息
  135. @param attachment: 附件
  136. @return: 附件上传处理信息
  137. """
  138. attachment["ftype"] = str(attachment["filename"]).split(".")[1]
  139. attachment["url"] = 'oss'
  140. attachment["fid"] = self.fid + "." + attachment["ftype"]
  141. attachment["size"] = self.file_size
  142. return attachment