Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

registry.py 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. import functools
  2. import sys
  3. import threading
  4. import warnings
  5. from collections import Counter, defaultdict
  6. from functools import partial
  7. from django.core.exceptions import AppRegistryNotReady, ImproperlyConfigured
  8. from .config import AppConfig
  9. class Apps:
  10. """
  11. A registry that stores the configuration of installed applications.
  12. It also keeps track of models, e.g. to provide reverse relations.
  13. """
  14. def __init__(self, installed_apps=()):
  15. # installed_apps is set to None when creating the main registry
  16. # because it cannot be populated at that point. Other registries must
  17. # provide a list of installed apps and are populated immediately.
  18. if installed_apps is None and hasattr(sys.modules[__name__], "apps"):
  19. raise RuntimeError("You must supply an installed_apps argument.")
  20. # Mapping of app labels => model names => model classes. Every time a
  21. # model is imported, ModelBase.__new__ calls apps.register_model which
  22. # creates an entry in all_models. All imported models are registered,
  23. # regardless of whether they're defined in an installed application
  24. # and whether the registry has been populated. Since it isn't possible
  25. # to reimport a module safely (it could reexecute initialization code)
  26. # all_models is never overridden or reset.
  27. self.all_models = defaultdict(dict)
  28. # Mapping of labels to AppConfig instances for installed apps.
  29. self.app_configs = {}
  30. # Stack of app_configs. Used to store the current state in
  31. # set_available_apps and set_installed_apps.
  32. self.stored_app_configs = []
  33. # Whether the registry is populated.
  34. self.apps_ready = self.models_ready = self.ready = False
  35. # For the autoreloader.
  36. self.ready_event = threading.Event()
  37. # Lock for thread-safe population.
  38. self._lock = threading.RLock()
  39. self.loading = False
  40. # Maps ("app_label", "modelname") tuples to lists of functions to be
  41. # called when the corresponding model is ready. Used by this class's
  42. # `lazy_model_operation()` and `do_pending_operations()` methods.
  43. self._pending_operations = defaultdict(list)
  44. # Populate apps and models, unless it's the main registry.
  45. if installed_apps is not None:
  46. self.populate(installed_apps)
  47. def populate(self, installed_apps=None):
  48. """
  49. Load application configurations and models.
  50. Import each application module and then each model module.
  51. It is thread-safe and idempotent, but not reentrant.
  52. """
  53. if self.ready:
  54. return
  55. # populate() might be called by two threads in parallel on servers
  56. # that create threads before initializing the WSGI callable.
  57. with self._lock:
  58. if self.ready:
  59. return
  60. # An RLock prevents other threads from entering this section. The
  61. # compare and set operation below is atomic.
  62. if self.loading:
  63. # Prevent reentrant calls to avoid running AppConfig.ready()
  64. # methods twice.
  65. raise RuntimeError("populate() isn't reentrant")
  66. self.loading = True
  67. # Phase 1: initialize app configs and import app modules.
  68. for entry in installed_apps:
  69. if isinstance(entry, AppConfig):
  70. app_config = entry
  71. else:
  72. app_config = AppConfig.create(entry)
  73. if app_config.label in self.app_configs:
  74. raise ImproperlyConfigured(
  75. "Application labels aren't unique, "
  76. "duplicates: %s" % app_config.label
  77. )
  78. self.app_configs[app_config.label] = app_config
  79. app_config.apps = self
  80. # Check for duplicate app names.
  81. counts = Counter(
  82. app_config.name for app_config in self.app_configs.values()
  83. )
  84. duplicates = [name for name, count in counts.most_common() if count > 1]
  85. if duplicates:
  86. raise ImproperlyConfigured(
  87. "Application names aren't unique, "
  88. "duplicates: %s" % ", ".join(duplicates)
  89. )
  90. self.apps_ready = True
  91. # Phase 2: import models modules.
  92. for app_config in self.app_configs.values():
  93. app_config.import_models()
  94. self.clear_cache()
  95. self.models_ready = True
  96. # Phase 3: run ready() methods of app configs.
  97. for app_config in self.get_app_configs():
  98. app_config.ready()
  99. self.ready = True
  100. self.ready_event.set()
  101. def check_apps_ready(self):
  102. """Raise an exception if all apps haven't been imported yet."""
  103. if not self.apps_ready:
  104. from django.conf import settings
  105. # If "not ready" is due to unconfigured settings, accessing
  106. # INSTALLED_APPS raises a more helpful ImproperlyConfigured
  107. # exception.
  108. settings.INSTALLED_APPS
  109. raise AppRegistryNotReady("Apps aren't loaded yet.")
  110. def check_models_ready(self):
  111. """Raise an exception if all models haven't been imported yet."""
  112. if not self.models_ready:
  113. raise AppRegistryNotReady("Models aren't loaded yet.")
  114. def get_app_configs(self):
  115. """Import applications and return an iterable of app configs."""
  116. self.check_apps_ready()
  117. return self.app_configs.values()
  118. def get_app_config(self, app_label):
  119. """
  120. Import applications and returns an app config for the given label.
  121. Raise LookupError if no application exists with this label.
  122. """
  123. self.check_apps_ready()
  124. try:
  125. return self.app_configs[app_label]
  126. except KeyError:
  127. message = "No installed app with label '%s'." % app_label
  128. for app_config in self.get_app_configs():
  129. if app_config.name == app_label:
  130. message += " Did you mean '%s'?" % app_config.label
  131. break
  132. raise LookupError(message)
  133. # This method is performance-critical at least for Django's test suite.
  134. @functools.lru_cache(maxsize=None)
  135. def get_models(self, include_auto_created=False, include_swapped=False):
  136. """
  137. Return a list of all installed models.
  138. By default, the following models aren't included:
  139. - auto-created models for many-to-many relations without
  140. an explicit intermediate table,
  141. - models that have been swapped out.
  142. Set the corresponding keyword argument to True to include such models.
  143. """
  144. self.check_models_ready()
  145. result = []
  146. for app_config in self.app_configs.values():
  147. result.extend(app_config.get_models(include_auto_created, include_swapped))
  148. return result
  149. def get_model(self, app_label, model_name=None, require_ready=True):
  150. """
  151. Return the model matching the given app_label and model_name.
  152. As a shortcut, app_label may be in the form <app_label>.<model_name>.
  153. model_name is case-insensitive.
  154. Raise LookupError if no application exists with this label, or no
  155. model exists with this name in the application. Raise ValueError if
  156. called with a single argument that doesn't contain exactly one dot.
  157. """
  158. if require_ready:
  159. self.check_models_ready()
  160. else:
  161. self.check_apps_ready()
  162. if model_name is None:
  163. app_label, model_name = app_label.split(".")
  164. app_config = self.get_app_config(app_label)
  165. if not require_ready and app_config.models is None:
  166. app_config.import_models()
  167. return app_config.get_model(model_name, require_ready=require_ready)
  168. def register_model(self, app_label, model):
  169. # Since this method is called when models are imported, it cannot
  170. # perform imports because of the risk of import loops. It mustn't
  171. # call get_app_config().
  172. model_name = model._meta.model_name
  173. app_models = self.all_models[app_label]
  174. if model_name in app_models:
  175. if (
  176. model.__name__ == app_models[model_name].__name__
  177. and model.__module__ == app_models[model_name].__module__
  178. ):
  179. warnings.warn(
  180. "Model '%s.%s' was already registered. Reloading models is not "
  181. "advised as it can lead to inconsistencies, most notably with "
  182. "related models." % (app_label, model_name),
  183. RuntimeWarning,
  184. stacklevel=2,
  185. )
  186. else:
  187. raise RuntimeError(
  188. "Conflicting '%s' models in application '%s': %s and %s."
  189. % (model_name, app_label, app_models[model_name], model)
  190. )
  191. app_models[model_name] = model
  192. self.do_pending_operations(model)
  193. self.clear_cache()
  194. def is_installed(self, app_name):
  195. """
  196. Check whether an application with this name exists in the registry.
  197. app_name is the full name of the app e.g. 'django.contrib.admin'.
  198. """
  199. self.check_apps_ready()
  200. return any(ac.name == app_name for ac in self.app_configs.values())
  201. def get_containing_app_config(self, object_name):
  202. """
  203. Look for an app config containing a given object.
  204. object_name is the dotted Python path to the object.
  205. Return the app config for the inner application in case of nesting.
  206. Return None if the object isn't in any registered app config.
  207. """
  208. self.check_apps_ready()
  209. candidates = []
  210. for app_config in self.app_configs.values():
  211. if object_name.startswith(app_config.name):
  212. subpath = object_name[len(app_config.name) :]
  213. if subpath == "" or subpath[0] == ".":
  214. candidates.append(app_config)
  215. if candidates:
  216. return sorted(candidates, key=lambda ac: -len(ac.name))[0]
  217. def get_registered_model(self, app_label, model_name):
  218. """
  219. Similar to get_model(), but doesn't require that an app exists with
  220. the given app_label.
  221. It's safe to call this method at import time, even while the registry
  222. is being populated.
  223. """
  224. model = self.all_models[app_label].get(model_name.lower())
  225. if model is None:
  226. raise LookupError("Model '%s.%s' not registered." % (app_label, model_name))
  227. return model
  228. @functools.lru_cache(maxsize=None)
  229. def get_swappable_settings_name(self, to_string):
  230. """
  231. For a given model string (e.g. "auth.User"), return the name of the
  232. corresponding settings name if it refers to a swappable model. If the
  233. referred model is not swappable, return None.
  234. This method is decorated with lru_cache because it's performance
  235. critical when it comes to migrations. Since the swappable settings don't
  236. change after Django has loaded the settings, there is no reason to get
  237. the respective settings attribute over and over again.
  238. """
  239. to_string = to_string.lower()
  240. for model in self.get_models(include_swapped=True):
  241. swapped = model._meta.swapped
  242. # Is this model swapped out for the model given by to_string?
  243. if swapped and swapped.lower() == to_string:
  244. return model._meta.swappable
  245. # Is this model swappable and the one given by to_string?
  246. if model._meta.swappable and model._meta.label_lower == to_string:
  247. return model._meta.swappable
  248. return None
  249. def set_available_apps(self, available):
  250. """
  251. Restrict the set of installed apps used by get_app_config[s].
  252. available must be an iterable of application names.
  253. set_available_apps() must be balanced with unset_available_apps().
  254. Primarily used for performance optimization in TransactionTestCase.
  255. This method is safe in the sense that it doesn't trigger any imports.
  256. """
  257. available = set(available)
  258. installed = {app_config.name for app_config in self.get_app_configs()}
  259. if not available.issubset(installed):
  260. raise ValueError(
  261. "Available apps isn't a subset of installed apps, extra apps: %s"
  262. % ", ".join(available - installed)
  263. )
  264. self.stored_app_configs.append(self.app_configs)
  265. self.app_configs = {
  266. label: app_config
  267. for label, app_config in self.app_configs.items()
  268. if app_config.name in available
  269. }
  270. self.clear_cache()
  271. def unset_available_apps(self):
  272. """Cancel a previous call to set_available_apps()."""
  273. self.app_configs = self.stored_app_configs.pop()
  274. self.clear_cache()
  275. def set_installed_apps(self, installed):
  276. """
  277. Enable a different set of installed apps for get_app_config[s].
  278. installed must be an iterable in the same format as INSTALLED_APPS.
  279. set_installed_apps() must be balanced with unset_installed_apps(),
  280. even if it exits with an exception.
  281. Primarily used as a receiver of the setting_changed signal in tests.
  282. This method may trigger new imports, which may add new models to the
  283. registry of all imported models. They will stay in the registry even
  284. after unset_installed_apps(). Since it isn't possible to replay
  285. imports safely (e.g. that could lead to registering listeners twice),
  286. models are registered when they're imported and never removed.
  287. """
  288. if not self.ready:
  289. raise AppRegistryNotReady("App registry isn't ready yet.")
  290. self.stored_app_configs.append(self.app_configs)
  291. self.app_configs = {}
  292. self.apps_ready = self.models_ready = self.loading = self.ready = False
  293. self.clear_cache()
  294. self.populate(installed)
  295. def unset_installed_apps(self):
  296. """Cancel a previous call to set_installed_apps()."""
  297. self.app_configs = self.stored_app_configs.pop()
  298. self.apps_ready = self.models_ready = self.ready = True
  299. self.clear_cache()
  300. def clear_cache(self):
  301. """
  302. Clear all internal caches, for methods that alter the app registry.
  303. This is mostly used in tests.
  304. """
  305. # Call expire cache on each model. This will purge
  306. # the relation tree and the fields cache.
  307. self.get_models.cache_clear()
  308. if self.ready:
  309. # Circumvent self.get_models() to prevent that the cache is refilled.
  310. # This particularly prevents that an empty value is cached while cloning.
  311. for app_config in self.app_configs.values():
  312. for model in app_config.get_models(include_auto_created=True):
  313. model._meta._expire_cache()
  314. def lazy_model_operation(self, function, *model_keys):
  315. """
  316. Take a function and a number of ("app_label", "modelname") tuples, and
  317. when all the corresponding models have been imported and registered,
  318. call the function with the model classes as its arguments.
  319. The function passed to this method must accept exactly n models as
  320. arguments, where n=len(model_keys).
  321. """
  322. # Base case: no arguments, just execute the function.
  323. if not model_keys:
  324. function()
  325. # Recursive case: take the head of model_keys, wait for the
  326. # corresponding model class to be imported and registered, then apply
  327. # that argument to the supplied function. Pass the resulting partial
  328. # to lazy_model_operation() along with the remaining model args and
  329. # repeat until all models are loaded and all arguments are applied.
  330. else:
  331. next_model, *more_models = model_keys
  332. # This will be executed after the class corresponding to next_model
  333. # has been imported and registered. The `func` attribute provides
  334. # duck-type compatibility with partials.
  335. def apply_next_model(model):
  336. next_function = partial(apply_next_model.func, model)
  337. self.lazy_model_operation(next_function, *more_models)
  338. apply_next_model.func = function
  339. # If the model has already been imported and registered, partially
  340. # apply it to the function now. If not, add it to the list of
  341. # pending operations for the model, where it will be executed with
  342. # the model class as its sole argument once the model is ready.
  343. try:
  344. model_class = self.get_registered_model(*next_model)
  345. except LookupError:
  346. self._pending_operations[next_model].append(apply_next_model)
  347. else:
  348. apply_next_model(model_class)
  349. def do_pending_operations(self, model):
  350. """
  351. Take a newly-prepared model and pass it to each function waiting for
  352. it. This is called at the very end of Apps.register_model().
  353. """
  354. key = model._meta.app_label, model._meta.model_name
  355. for function in self._pending_operations.pop(key, []):
  356. function(model)
  357. apps = Apps(installed_apps=None)