oss_client.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import oss2
  2. import os
  3. class OSSClient:
  4. # 配置默认的 endpoint 地址
  5. DEFAULT_ENDPOINT = "oss-cn-hangzhou.aliyuncs.com" # 默认华东1区(杭州)
  6. def __init__(self, access_key_id=None, access_key_secret=None, bucket_name=None):
  7. """
  8. 初始化 OSS 客户端
  9. :param bucket_name: Bucket 名称
  10. """
  11. # 从环境变量中获取 Access Key 和 Secret
  12. if access_key_id is None or access_key_secret is None:
  13. access_key_id = "LTAIP6x1l3DXfSxm"
  14. access_key_secret = "KbTaM9ars4OX3PMS6Xm7rtxGr1FLon"
  15. if bucket_name is None:
  16. bucket_name = "art-pubbucket"
  17. # 检查是否有凭证
  18. if not access_key_id or not access_key_secret:
  19. raise ValueError(
  20. "ACCESS_KEY_ID and ACCESS_KEY_SECRET must be set in the environment variables."
  21. )
  22. # 使用默认的 endpoint 地址
  23. self.auth = oss2.Auth(access_key_id, access_key_secret)
  24. self.bucket = oss2.Bucket(self.auth, self.DEFAULT_ENDPOINT, bucket_name)
  25. def upload_file(self, local_file_path, oss_file_path):
  26. """
  27. 上传文件到 OSS
  28. :param local_file_path: 本地文件路径
  29. :param oss_file_path: OSS 存储的文件路径(例如:pdfs/myfile.pdf)
  30. :return: 上传结果,成功返回文件信息,失败抛出异常
  31. """
  32. if not os.path.exists(local_file_path):
  33. raise FileNotFoundError(f"Local file {local_file_path} does not exist.")
  34. try:
  35. self.bucket.put_object_from_file(oss_file_path, local_file_path)
  36. return {"status": "success", "message": f"File uploaded to {oss_file_path}"}
  37. except Exception as e:
  38. raise Exception(f"Error uploading file to OSS: {str(e)}")
  39. def download_file(self, oss_file_path, local_file_path):
  40. """
  41. 从 OSS 下载文件
  42. :param oss_file_path: OSS 文件路径(例如:pdfs/myfile.pdf)
  43. :param local_file_path: 本地保存路径
  44. :return: 下载结果,成功返回下载文件的路径,失败抛出异常
  45. """
  46. try:
  47. self.bucket.get_object_to_file(oss_file_path, local_file_path)
  48. return {
  49. "status": "success",
  50. "message": f"File downloaded to {local_file_path}",
  51. }
  52. except Exception as e:
  53. raise Exception(f"Error downloading file from OSS: {str(e)}")
  54. def delete_file(self, oss_file_path):
  55. """
  56. 从 OSS 删除文件
  57. :param oss_file_path: OSS 文件路径(例如:pdfs/myfile.pdf)
  58. :return: 删除结果,成功返回消息,失败抛出异常
  59. """
  60. try:
  61. self.bucket.delete_object(oss_file_path)
  62. return {
  63. "status": "success",
  64. "message": f"File {oss_file_path} deleted from OSS",
  65. }
  66. except Exception as e:
  67. raise Exception(f"Error deleting file from OSS: {str(e)}")
  68. def file_exists(self, oss_file_path):
  69. """
  70. 检查文件是否存在于 OSS 中
  71. :param oss_file_path: OSS 文件路径(例如:pdfs/myfile.pdf)
  72. :return: 布尔值,文件存在返回 True,文件不存在返回 False
  73. """
  74. try:
  75. self.bucket.get_object(oss_file_path)
  76. return True
  77. except oss2.exceptions.NoSuchKey:
  78. return False
  79. except Exception as e:
  80. raise Exception(f"Error checking file existence on OSS: {str(e)}")