handler.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from django.conf import DEFAULT_STORAGE_ALIAS, STATICFILES_STORAGE_ALIAS, settings
  2. from django.core.exceptions import ImproperlyConfigured
  3. from django.utils.functional import cached_property
  4. from django.utils.module_loading import import_string
  5. class InvalidStorageError(ImproperlyConfigured):
  6. pass
  7. class StorageHandler:
  8. def __init__(self, backends=None):
  9. # backends is an optional dict of storage backend definitions
  10. # (structured like settings.STORAGES).
  11. self._backends = backends
  12. self._storages = {}
  13. @cached_property
  14. def backends(self):
  15. if self._backends is None:
  16. self._backends = settings.STORAGES.copy()
  17. # RemovedInDjango51Warning.
  18. if settings.is_overridden("DEFAULT_FILE_STORAGE"):
  19. self._backends[DEFAULT_STORAGE_ALIAS] = {
  20. "BACKEND": settings.DEFAULT_FILE_STORAGE
  21. }
  22. if settings.is_overridden("STATICFILES_STORAGE"):
  23. self._backends[STATICFILES_STORAGE_ALIAS] = {
  24. "BACKEND": settings.STATICFILES_STORAGE
  25. }
  26. return self._backends
  27. def __getitem__(self, alias):
  28. try:
  29. return self._storages[alias]
  30. except KeyError:
  31. try:
  32. params = self.backends[alias]
  33. except KeyError:
  34. raise InvalidStorageError(
  35. f"Could not find config for '{alias}' in settings.STORAGES."
  36. )
  37. storage = self.create_storage(params)
  38. self._storages[alias] = storage
  39. return storage
  40. def create_storage(self, params):
  41. params = params.copy()
  42. backend = params.pop("BACKEND")
  43. options = params.pop("OPTIONS", {})
  44. try:
  45. storage_cls = import_string(backend)
  46. except ImportError as e:
  47. raise InvalidStorageError(f"Could not find backend {backend!r}: {e}") from e
  48. return storage_cls(**options)