aliyun.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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,count=0, **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. filname = hashlib.md5(attachment["filename"].encode("utf-8"))
  74. filname = filname.hexdigest() #加密1次
  75. types = attachment["ftype"]
  76. self.file_path = "{}/{}".format(img_dir, filname+'.'+types)
  77. with open(self.file_path, 'wb') as f:
  78. f.write(self.file_stream)
  79. # 上传附件
  80. self.put_oss_from_local()
  81. file_state = self.file_state(attachment)
  82. # 删除附件
  83. os.remove(self.file_path)
  84. # 返回附件上传处理信息
  85. return file_state
  86. else:
  87. if count<3:
  88. self.post_state(attachment,count=count+1, **kwargs)
  89. else:
  90. # attachment["ftype"] = str(attachment["filename"]).split(".")[1]
  91. attachment["url"] = 'oss'
  92. attachment["fid"] = self.fid + "." + attachment["ftype"]
  93. attachment["size"] = '0kb'
  94. attachment["false"] = True
  95. return attachment
  96. def post_state(self, attachment,count=0, **kwargs):
  97. """
  98. 下载附件并上传阿里oss
  99. @param attachment: 附件
  100. @return: 附件处理结果
  101. """
  102. request_params = {
  103. 'headers': setting.headers,
  104. 'timeout': 20,
  105. 'stream': True,
  106. **kwargs
  107. }
  108. with requests.post(attachment["org_url"], **request_params) as req:
  109. if req.status_code == 200:
  110. self.file_stream = req.content
  111. img_dir = f"file/{attachment['channel']}"
  112. # 文件夹不存在则创建文件夹
  113. if not os.path.exists(img_dir):
  114. os.makedirs(img_dir, mode=0o777, exist_ok=True)
  115. # 打开目录,放入下载的附件
  116. filname = hashlib.md5(attachment["filename"].encode("utf-8"))
  117. filname = filname.hexdigest() # 加密1次
  118. types = attachment["ftype"]
  119. self.file_path = "{}/{}".format(img_dir, filname + '.' + types)
  120. with open(self.file_path, 'wb') as f:
  121. f.write(self.file_stream)
  122. # 上传附件
  123. self.put_oss_from_local()
  124. file_state = self.file_state(attachment)
  125. # 删除附件
  126. # os.remove(self.file_path)
  127. # 返回附件上传处理信息
  128. return file_state
  129. else:
  130. if count<3:
  131. self.post_state(attachment,count=count+1, **kwargs)
  132. else:
  133. attachment["url"] = 'oss'
  134. attachment["fid"] = self.fid + "." + attachment["ftype"]
  135. attachment["size"] = '0kb'
  136. attachment["false"] = True
  137. return attachment
  138. def put_oss_from_local(self):
  139. """上传一个本地文件到阿里OSS的普通文件"""
  140. auth = oss2.Auth(self.__acc_key_id, self.__acc_key_secret)
  141. bucket = oss2.Bucket(auth, self.__endpoint, self.__bucket_name)
  142. bucket.put_object_from_file(self.fid, self.file_path)
  143. def file_state(self, attachment):
  144. """
  145. 文件信息
  146. @param attachment: 附件
  147. @return: 附件上传处理信息
  148. """
  149. # attachment["ftype"] = str(attachment["filename"]).split(".")[1]
  150. attachment["url"] = 'oss'
  151. attachment["fid"] = self.fid + "." + attachment["ftype"]
  152. attachment["size"] = self.file_size
  153. return attachment