OSSClient.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import logging
  2. import oss2
  3. from oss2.credentials import StaticCredentialsProvider
  4. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  5. class OSSClient(object):
  6. def __init__(self, access_key, access_secret, endpoint, region):
  7. print(f"oss.version: {oss2.__version__}")
  8. self.access_key = access_key
  9. self.access_secret = access_secret
  10. self.endpoint = endpoint
  11. self.region = region
  12. self.auth = oss2.ProviderAuthV4(StaticCredentialsProvider(self.access_key, self.access_secret))
  13. def download_file(self, bucket_name, oss_file_path, local_file_path):
  14. bucket = self._get_bucket(bucket_name)
  15. bucket.get_object_to_file(oss_file_path, local_file_path)
  16. def file_is_exist(self, bucket_name, oss_file_path) -> bool:
  17. """
  18. 检查阿里云 OSS 文件是否存在。
  19. :param bucket_name: OSS Bucket 名称
  20. :param oss_file_path: 文件路径,例如 'folder/file.txt'
  21. :return: 布尔值,表示文件是否存在
  22. """
  23. try:
  24. bucket = self._get_bucket(bucket_name)
  25. exists = bucket.object_exists(oss_file_path)
  26. return exists
  27. except Exception as e:
  28. return False
  29. def _get_bucket(self, bucket_name: str):
  30. return oss2.Bucket(auth=self.auth, endpoint=self.endpoint, bucket_name=bucket_name, region=self.region)