aliyun_storage.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from collections.abc import Generator
  2. from contextlib import closing
  3. import oss2 as aliyun_s3
  4. from flask import Flask
  5. from extensions.storage.base_storage import BaseStorage
  6. class AliyunStorage(BaseStorage):
  7. """Implementation for aliyun storage."""
  8. def __init__(self, app: Flask):
  9. super().__init__(app)
  10. app_config = self.app.config
  11. self.bucket_name = app_config.get("ALIYUN_OSS_BUCKET_NAME")
  12. oss_auth_method = aliyun_s3.Auth
  13. region = None
  14. if app_config.get("ALIYUN_OSS_AUTH_VERSION") == "v4":
  15. oss_auth_method = aliyun_s3.AuthV4
  16. region = app_config.get("ALIYUN_OSS_REGION")
  17. oss_auth = oss_auth_method(app_config.get("ALIYUN_OSS_ACCESS_KEY"), app_config.get("ALIYUN_OSS_SECRET_KEY"))
  18. self.client = aliyun_s3.Bucket(
  19. oss_auth,
  20. app_config.get("ALIYUN_OSS_ENDPOINT"),
  21. self.bucket_name,
  22. connect_timeout=30,
  23. region=region,
  24. )
  25. def save(self, filename, data):
  26. self.client.put_object(filename, data)
  27. def load_once(self, filename: str) -> bytes:
  28. with closing(self.client.get_object(filename)) as obj:
  29. data = obj.read()
  30. return data
  31. def load_stream(self, filename: str) -> Generator:
  32. def generate(filename: str = filename) -> Generator:
  33. with closing(self.client.get_object(filename)) as obj:
  34. while chunk := obj.read(4096):
  35. yield chunk
  36. return generate()
  37. def download(self, filename, target_filepath):
  38. self.client.get_object_to_file(filename, target_filepath)
  39. def exists(self, filename):
  40. return self.client.object_exists(filename)
  41. def delete(self, filename):
  42. self.client.delete_object(filename)