s3_storage.py 2.6 KB

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