oracle_oci_storage.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from collections.abc import Generator
  2. from contextlib import closing
  3. import boto3
  4. from botocore.exceptions import ClientError
  5. from flask import Flask
  6. from extensions.storage.base_storage import BaseStorage
  7. class OracleOCIStorage(BaseStorage):
  8. """Implementation for Oracle OCI storage."""
  9. def __init__(self, app: Flask):
  10. super().__init__(app)
  11. app_config = self.app.config
  12. self.bucket_name = app_config.get("OCI_BUCKET_NAME")
  13. self.client = boto3.client(
  14. "s3",
  15. aws_secret_access_key=app_config.get("OCI_SECRET_KEY"),
  16. aws_access_key_id=app_config.get("OCI_ACCESS_KEY"),
  17. endpoint_url=app_config.get("OCI_ENDPOINT"),
  18. region_name=app_config.get("OCI_REGION"),
  19. )
  20. def save(self, filename, data):
  21. self.client.put_object(Bucket=self.bucket_name, Key=filename, Body=data)
  22. def load_once(self, filename: str) -> bytes:
  23. try:
  24. with closing(self.client) as client:
  25. data = client.get_object(Bucket=self.bucket_name, Key=filename)["Body"].read()
  26. except ClientError as ex:
  27. if ex.response["Error"]["Code"] == "NoSuchKey":
  28. raise FileNotFoundError("File not found")
  29. else:
  30. raise
  31. return data
  32. def load_stream(self, filename: str) -> Generator:
  33. def generate(filename: str = filename) -> Generator:
  34. try:
  35. with closing(self.client) as client:
  36. response = client.get_object(Bucket=self.bucket_name, Key=filename)
  37. yield from response["Body"].iter_chunks()
  38. except ClientError as ex:
  39. if ex.response["Error"]["Code"] == "NoSuchKey":
  40. raise FileNotFoundError("File not found")
  41. else:
  42. raise
  43. return generate()
  44. def download(self, filename, target_filepath):
  45. with closing(self.client) as client:
  46. client.download_file(self.bucket_name, filename, target_filepath)
  47. def exists(self, filename):
  48. with closing(self.client) as client:
  49. try:
  50. client.head_object(Bucket=self.bucket_name, Key=filename)
  51. return True
  52. except:
  53. return False
  54. def delete(self, filename):
  55. self.client.delete_object(Bucket=self.bucket_name, Key=filename)