oss_client.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import hashlib
  2. import json
  3. from minio import Minio, S3Error
  4. from tools.logger_handle import logger
  5. class MinioClient:
  6. client = None
  7. def __new__(cls, *args, **kwargs):
  8. if not cls.client:
  9. cls.client = object.__new__(cls)
  10. return cls.client
  11. def __init__(self, service, access_key, secret_key, secure=False):
  12. self.service = service
  13. self.access_key = access_key
  14. self.secret_key = secret_key
  15. self.client = Minio(service, access_key=access_key, secret_key=secret_key, secure=secure)
  16. @staticmethod
  17. def load_metadata(local_path):
  18. with open(f'{local_path}.metadata', 'r', encoding='utf-8') as f:
  19. file_metadata = json.loads(f.read())
  20. return file_metadata
  21. def get_bucket_list(self):
  22. buckets = self.client.list_buckets()
  23. bucket_list = []
  24. for bucket in buckets:
  25. bucket_list.append(
  26. {"bucket_name": bucket.name, "create_time": bucket.creation_date}
  27. )
  28. return bucket_list
  29. def upload_file(self, file_path):
  30. """
  31. 上传文件 + 写入
  32. :param file_path: 本地文件路径
  33. :return:
  34. """
  35. try:
  36. with open(f'{file_path}.metadata', 'r', encoding='utf-8') as f:
  37. file_metadata = json.loads(f.read())
  38. oss_path = file_metadata['oss_path']
  39. self.client.fput_object(file_metadata['bucket_name'], oss_path, file_path)
  40. return True
  41. except S3Error as e:
  42. logger.exception(e)
  43. return False
  44. def fget_file(self, bucket_name, oss_path, file_path):
  45. """
  46. 下载保存文件保存本地
  47. :param bucket_name:
  48. :param oss_path:服务端文件名
  49. :param file_path:要写入的本地路径
  50. :return:
  51. """
  52. self.client.fget_object(bucket_name, oss_path, file_path)
  53. with open(f'{file_path}.metadata', 'w', encoding='utf-8') as f:
  54. f.write(json.dumps({
  55. 'serve': self.service,
  56. 'access_key': self.access_key,
  57. 'secret_key': self.secret_key,
  58. 'bucket_name': bucket_name,
  59. 'md5': self.get_cloud_file_md5(bucket_name, oss_path),
  60. 'oss_path': oss_path,
  61. 'last_modified': self.get_cloud_last_modified(bucket_name, oss_path)
  62. }))
  63. def get_cloud_file_md5(self, bucket_name, file):
  64. return self.client.stat_object(bucket_name, file).etag
  65. def get_cloud_last_modified(self, bucket_name, file):
  66. return self.client.stat_object(bucket_name, file).last_modified.strftime("%Y-%m-%d %H:%M:%S")
  67. @staticmethod
  68. def get_file_md5(file_path):
  69. md5 = hashlib.md5()
  70. with open(file_path, 'rb') as f:
  71. # 分块读取以支持大文件
  72. while chunk := f.read(8192):
  73. md5.update(chunk)
  74. return md5.hexdigest()
  75. # oss_config = get_config('oss')
  76. # oss_handle = MinioClient(oss_config['endpoint'],
  77. # access_key=oss_config['access_key'],
  78. # secret_key=oss_config['secret_key'])
  79. if __name__ == '__main__':
  80. client = MinioClient('172.10.3.36:9000', access_key='miniominio', secret_key='miniominio')
  81. # print(client.get_cloud_file_md5('document-mgr', '接口文档.txt'))
  82. # print(client.get_file_md5('接口文档.txt'))
  83. print(client.get_cloud_file_md5('document-mgr', 'test.docx'))
  84. print(client.upload_file(r'E:\PycharmProjects\office_plugin\tools\storage\admin\document-mgr_test.docx'))
  85. oss_path = 'test.docx'
  86. print(client.get_cloud_file_md5('document-mgr', 'test.docx'))