oss_client.py 3.9 KB

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