storage_backends.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # Copy from https://github.com/silentsokolov/flask-thumbnails/blob/master/flask_thumbnails/storage_backends.py
  2. import errno
  3. import os
  4. from abc import ABC, abstractmethod
  5. class BaseStorageBackend(ABC):
  6. def __init__(self, app=None):
  7. self.app = app
  8. @abstractmethod
  9. def read(self, filepath, mode="rb", **kwargs):
  10. raise NotImplementedError
  11. @abstractmethod
  12. def exists(self, filepath):
  13. raise NotImplementedError
  14. @abstractmethod
  15. def save(self, filepath, data):
  16. raise NotImplementedError
  17. class FilesystemStorageBackend(BaseStorageBackend):
  18. def read(self, filepath, mode="rb", **kwargs):
  19. with open(filepath, mode) as f: # pylint: disable=unspecified-encoding
  20. return f.read()
  21. def exists(self, filepath):
  22. return os.path.exists(filepath)
  23. def save(self, filepath, data):
  24. directory = os.path.dirname(filepath)
  25. if not os.path.exists(directory):
  26. try:
  27. os.makedirs(directory)
  28. except OSError as e:
  29. if e.errno != errno.EEXIST:
  30. raise
  31. if not os.path.isdir(directory):
  32. raise IOError("{} is not a directory".format(directory))
  33. with open(filepath, "wb") as f:
  34. f.write(data)