File: handler.py

package info (click to toggle)
python-django 3%3A4.2.24-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 58,604 kB
  • sloc: python: 334,766; javascript: 18,754; xml: 215; makefile: 178; sh: 27
file content (55 lines) | stat: -rw-r--r-- 1,999 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
from django.conf import DEFAULT_STORAGE_ALIAS, STATICFILES_STORAGE_ALIAS, settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.functional import cached_property
from django.utils.module_loading import import_string


class InvalidStorageError(ImproperlyConfigured):
    pass


class StorageHandler:
    def __init__(self, backends=None):
        # backends is an optional dict of storage backend definitions
        # (structured like settings.STORAGES).
        self._backends = backends
        self._storages = {}

    @cached_property
    def backends(self):
        if self._backends is None:
            self._backends = settings.STORAGES.copy()
            # RemovedInDjango51Warning.
            if settings.is_overridden("DEFAULT_FILE_STORAGE"):
                self._backends[DEFAULT_STORAGE_ALIAS] = {
                    "BACKEND": settings.DEFAULT_FILE_STORAGE
                }
            if settings.is_overridden("STATICFILES_STORAGE"):
                self._backends[STATICFILES_STORAGE_ALIAS] = {
                    "BACKEND": settings.STATICFILES_STORAGE
                }
        return self._backends

    def __getitem__(self, alias):
        try:
            return self._storages[alias]
        except KeyError:
            try:
                params = self.backends[alias]
            except KeyError:
                raise InvalidStorageError(
                    f"Could not find config for '{alias}' in settings.STORAGES."
                )
            storage = self.create_storage(params)
            self._storages[alias] = storage
            return storage

    def create_storage(self, params):
        params = params.copy()
        backend = params.pop("BACKEND")
        options = params.pop("OPTIONS", {})
        try:
            storage_cls = import_string(backend)
        except ImportError as e:
            raise InvalidStorageError(f"Could not find backend {backend!r}: {e}") from e
        return storage_cls(**options)