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