Debian Codegraph @

django/apps/config.py

raw
1 import inspect
2 import os
3 from importlib import import_module
4
5 from django.core.exceptions import ImproperlyConfigured
6 from django.utils.functional import cached_property
7 from django.utils.module_loading import import_string, module_has_submodule
8
9 APPS_MODULE_NAME = "apps"
10 MODELS_MODULE_NAME = "models"
11
12
13 class AppConfig:
14 """Class representing a Django application and its configuration."""
15
16 def __init__(self, app_name, app_module):
17 # Full Python path to the application e.g. 'django.contrib.admin'.
18 self.name = app_name
19
20 # Root module for the application e.g. <module 'django.contrib.admin'
21 # from 'django/contrib/admin/__init__.py'>.
22 self.module = app_module
23
24 # Reference to the Apps registry that holds this AppConfig. Set by the
25 # registry when it registers the AppConfig instance.
26 self.apps = None
27
28 # The following attributes could be defined at the class level in a
29 # subclass, hence the test-and-set pattern.
30
31 # Last component of the Python path to the application e.g. 'admin'.
32 # This value must be unique across a Django project.
33 if not hasattr(self, "label"):
34 self.label = app_name.rpartition(".")[2]
35 if not self.label.isidentifier():
36 raise ImproperlyConfigured(
37 "The app label '%s' is not a valid Python identifier." % self.label
38 )
39
40 # Human-readable name for the application e.g. "Admin".
41 if not hasattr(self, "verbose_name"):
42 self.verbose_name = self.label.title()
43
44 # Filesystem path to the application directory e.g.
45 # '/path/to/django/contrib/admin'.
46 if not hasattr(self, "path"):
47 self.path = self._path_from_module(app_module)
48
49 # Module containing models e.g. <module 'django.contrib.admin.models'
50 # from 'django/contrib/admin/models.py'>. Set by import_models().
51 # None if the application doesn't have a models module.
52 self.models_module = None
53
54 # Mapping of lowercase model names to model classes. Initially set to
55 # None to prevent accidental access before import_models() runs.
56 self.models = None
57
58 def __repr__(self):
59 return "<%s: %s>" % (self.__class__.__name__, self.label)
60
61 @cached_property
62 def default_auto_field(self):
63 from django.conf import settings
64
65 return settings.DEFAULT_AUTO_FIELD
66
67 @property
68 def _is_default_auto_field_overridden(self):
69 return self.__class__.default_auto_field is not AppConfig.default_auto_field
70
71 def _path_from_module(self, module):
72 """Attempt to determine app's filesystem path from its module."""
73 # See #21874 for extended discussion of the behavior of this method in
74 # various cases.
75 # Convert to list because __path__ may not support indexing.
76 paths = list(getattr(module, "__path__", []))
77 if len(paths) != 1:
78 filename = getattr(module, "__file__", None)
79 if filename is not None:
80 paths = [os.path.dirname(filename)]
81 else:
82 # For unknown reasons, sometimes the list returned by __path__
83 # contains duplicates that must be removed (#25246).
84 paths = list(set(paths))
85 if len(paths) > 1:
86 raise ImproperlyConfigured(
87 "The app module %r has multiple filesystem locations (%r); "
88 "you must configure this app with an AppConfig subclass "
89 "with a 'path' class attribute." % (module, paths)
90 )
91 elif not paths:
92 raise ImproperlyConfigured(
93 "The app module %r has no filesystem location, "
94 "you must configure this app with an AppConfig subclass "
95 "with a 'path' class attribute." % module
96 )
97 return paths[0]
98
99 @classmethod
100 def create(cls, entry):
101 """
102 Factory that creates an app config from an entry in INSTALLED_APPS.
103 """
104 # create() eventually returns app_config_class(app_name, app_module).
105 app_config_class = None
106 app_name = None
107 app_module = None
108
109 # If import_module succeeds, entry points to the app module.
110 try:
111 app_module = import_module(entry)
112 except Exception:
113 pass
114 else:
115 # If app_module has an apps submodule that defines a single
116 # AppConfig subclass, use it automatically.
117 # To prevent this, an AppConfig subclass can declare a class
118 # variable default = False.
119 # If the apps module defines more than one AppConfig subclass,
120 # the default one can declare default = True.
121 if module_has_submodule(app_module, APPS_MODULE_NAME):
122 mod_path = "%s.%s" % (entry, APPS_MODULE_NAME)
123 mod = import_module(mod_path)
124 # Check if there's exactly one AppConfig candidate,
125 # excluding those that explicitly define default = False.
126 app_configs = [
127 (name, candidate)
128 for name, candidate in inspect.getmembers(mod, inspect.isclass)
129 if (
130 issubclass(candidate, cls)
131 and candidate is not cls
132 and getattr(candidate, "default", True)
133 )
134 ]
135 if len(app_configs) == 1:
136 app_config_class = app_configs[0][1]
137 else:
138 # Check if there's exactly one AppConfig subclass,
139 # among those that explicitly define default = True.
140 app_configs = [
141 (name, candidate)
142 for name, candidate in app_configs
143 if getattr(candidate, "default", False)
144 ]
145 if len(app_configs) > 1:
146 candidates = [repr(name) for name, _ in app_configs]
147 raise RuntimeError(
148 "%r declares more than one default AppConfig: "
149 "%s." % (mod_path, ", ".join(candidates))
150 )
151 elif len(app_configs) == 1:
152 app_config_class = app_configs[0][1]
153
154 # Use the default app config class if we didn't find anything.
155 if app_config_class is None:
156 app_config_class = cls
157 app_name = entry
158
159 # If import_string succeeds, entry is an app config class.
160 if app_config_class is None:
161 try:
162 app_config_class = import_string(entry)
163 except Exception:
164 pass
165 # If both import_module and import_string failed, it means that entry
166 # doesn't have a valid value.
167 if app_module is None and app_config_class is None:
168 # If the last component of entry starts with an uppercase letter,
169 # then it was likely intended to be an app config class; if not,
170 # an app module. Provide a nice error message in both cases.
171 mod_path, _, cls_name = entry.rpartition(".")
172 if mod_path and cls_name[0].isupper():
173 # We could simply re-trigger the string import exception, but
174 # we're going the extra mile and providing a better error
175 # message for typos in INSTALLED_APPS.
176 # This may raise ImportError, which is the best exception
177 # possible if the module at mod_path cannot be imported.
178 mod = import_module(mod_path)
179 candidates = [
180 repr(name)
181 for name, candidate in inspect.getmembers(mod, inspect.isclass)
182 if issubclass(candidate, cls) and candidate is not cls
183 ]
184 msg = "Module '%s' does not contain a '%s' class." % (
185 mod_path,
186 cls_name,
187 )
188 if candidates:
189 msg += " Choices are: %s." % ", ".join(candidates)
190 raise ImportError(msg)
191 else:
192 # Re-trigger the module import exception.
193 import_module(entry)
194
195 # Check for obvious errors. (This check prevents duck typing, but
196 # it could be removed if it became a problem in practice.)
197 if not issubclass(app_config_class, AppConfig):
198 raise ImproperlyConfigured("'%s' isn't a subclass of AppConfig." % entry)
199
200 # Obtain app name here rather than in AppClass.__init__ to keep
201 # all error checking for entries in INSTALLED_APPS in one place.
202 if app_name is None:
203 try:
204 app_name = app_config_class.name
205 except AttributeError:
206 raise ImproperlyConfigured("'%s' must supply a name attribute." % entry)
207
208 # Ensure app_name points to a valid module.
209 try:
210 app_module = import_module(app_name)
211 except ImportError:
212 raise ImproperlyConfigured(
213 "Cannot import '%s'. Check that '%s.%s.name' is correct."
214 % (
215 app_name,
216 app_config_class.__module__,
217 app_config_class.__qualname__,
218 )
219 )
220
221 # Entry is a path to an app config class.
222 return app_config_class(app_name, app_module)
223
224 def get_model(self, model_name, require_ready=True):
225 """
226 Return the model with the given case-insensitive model_name.
227
228 Raise LookupError if no model exists with this name.
229 """
230 if require_ready:
231 self.apps.check_models_ready()
232 else:
233 self.apps.check_apps_ready()
234 try:
235 return self.models[model_name.lower()]
236 except KeyError:
237 raise LookupError(
238 "App '%s' doesn't have a '%s' model." % (self.label, model_name)
239 )
240
241 def get_models(self, include_auto_created=False, include_swapped=False):
242 """
243 Return an iterable of models.
244
245 By default, the following models aren't included:
246
247 - auto-created models for many-to-many relations without
248 an explicit intermediate table,
249 - models that have been swapped out.
250
251 Set the corresponding keyword argument to True to include such models.
252 Keyword arguments aren't documented; they're a private API.
253 """
254 self.apps.check_models_ready()
255 for model in self.models.values():
256 if model._meta.auto_created and not include_auto_created:
257 continue
258 if model._meta.swapped and not include_swapped:
259 continue
260 yield model
261
262 def import_models(self):
263 # Dictionary of models for this app, primarily maintained in the
264 # 'all_models' attribute of the Apps this AppConfig is attached to.
265 self.models = self.apps.all_models[self.label]
266
267 if module_has_submodule(self.module, MODELS_MODULE_NAME):
268 models_module_name = "%s.%s" % (self.name, MODELS_MODULE_NAME)
269 self.models_module = import_module(models_module_name)
270
271 def ready(self):
272 """
273 Override this method in subclasses to run code when Django starts.
274 """