oss_client.py 3.6 KB

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