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

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