registry.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. import sys
  2. import threading
  3. import warnings
  4. from collections import Counter, OrderedDict, defaultdict
  5. from functools import partial
  6. from django.core.exceptions import AppRegistryNotReady, ImproperlyConfigured
  7. from django.utils import lru_cache
  8. from .config import AppConfig
  9. class Apps(object):
  10. """
  11. A registry that stores the configuration of installed applications.
  12. It also keeps track of models eg. 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. # Lock for thread-safe population.
  36. self._lock = threading.Lock()
  37. # Maps ("app_label", "modelname") tuples to lists of functions to be
  38. # called when the corresponding model is ready. Used by this class's
  39. # `lazy_model_operation()` and `do_pending_operations()` methods.
  40. self._pending_operations = defaultdict(list)
  41. # Populate apps and models, unless it's the master registry.
  42. if installed_apps is not None:
  43. self.populate(installed_apps)
  44. def populate(self, installed_apps=None):
  45. """
  46. Loads application configurations and models.
  47. This method imports each application module and then each model module.
  48. It is thread safe and idempotent, but not reentrant.
  49. """
  50. if self.ready:
  51. return
  52. # populate() might be called by two threads in parallel on servers
  53. # that create threads before initializing the WSGI callable.
  54. with self._lock:
  55. if self.ready:
  56. return
  57. # app_config should be pristine, otherwise the code below won't
  58. # guarantee that the order matches the order in INSTALLED_APPS.
  59. if self.app_configs:
  60. raise RuntimeError("populate() isn't reentrant")
  61. # Phase 1: initialize app configs and import app modules.
  62. for entry in installed_apps:
  63. if isinstance(entry, AppConfig):
  64. app_config = entry
  65. else:
  66. app_config = AppConfig.create(entry)
  67. if app_config.label in self.app_configs:
  68. raise ImproperlyConfigured(
  69. "Application labels aren't unique, "
  70. "duplicates: %s" % app_config.label)
  71. self.app_configs[app_config.label] = app_config
  72. app_config.apps = self
  73. # Check for duplicate app names.
  74. counts = Counter(
  75. app_config.name for app_config in self.app_configs.values())
  76. duplicates = [
  77. name for name, count in counts.most_common() if count > 1]
  78. if duplicates:
  79. raise ImproperlyConfigured(
  80. "Application names aren't unique, "
  81. "duplicates: %s" % ", ".join(duplicates))
  82. self.apps_ready = True
  83. # Phase 2: import models modules.
  84. for app_config in self.app_configs.values():
  85. app_config.import_models()
  86. self.clear_cache()
  87. self.models_ready = True
  88. # Phase 3: run ready() methods of app configs.
  89. for app_config in self.get_app_configs():
  90. app_config.ready()
  91. self.ready = True
  92. def check_apps_ready(self):
  93. """
  94. Raises an exception if all apps haven't been imported yet.
  95. """
  96. if not self.apps_ready:
  97. raise AppRegistryNotReady("Apps aren't loaded yet.")
  98. def check_models_ready(self):
  99. """
  100. Raises an exception if all models haven't been imported yet.
  101. """
  102. if not self.models_ready:
  103. raise AppRegistryNotReady("Models aren't loaded yet.")
  104. def get_app_configs(self):
  105. """
  106. Imports applications and returns an iterable of app configs.
  107. """
  108. self.check_apps_ready()
  109. return self.app_configs.values()
  110. def get_app_config(self, app_label):
  111. """
  112. Imports applications and returns an app config for the given label.
  113. Raises LookupError if no application exists with this label.
  114. """
  115. self.check_apps_ready()
  116. try:
  117. return self.app_configs[app_label]
  118. except KeyError:
  119. message = "No installed app with label '%s'." % app_label
  120. for app_config in self.get_app_configs():
  121. if app_config.name == app_label:
  122. message += " Did you mean '%s'?" % app_config.label
  123. break
  124. raise LookupError(message)
  125. # This method is performance-critical at least for Django's test suite.
  126. @lru_cache.lru_cache(maxsize=None)
  127. def get_models(self, include_auto_created=False, include_swapped=False):
  128. """
  129. Returns a list of all installed models.
  130. By default, the following models aren't included:
  131. - auto-created models for many-to-many relations without
  132. an explicit intermediate table,
  133. - models created to satisfy deferred attribute queries,
  134. - models that have been swapped out.
  135. Set the corresponding keyword argument to True to include such models.
  136. """
  137. self.check_models_ready()
  138. result = []
  139. for app_config in self.app_configs.values():
  140. result.extend(list(app_config.get_models(include_auto_created, include_swapped)))
  141. return result
  142. def get_model(self, app_label, model_name=None, require_ready=True):
  143. """
  144. Returns the model matching the given app_label and model_name.
  145. As a shortcut, this function also accepts a single argument in the
  146. form <app_label>.<model_name>.
  147. model_name is case-insensitive.
  148. Raises LookupError if no application exists with this label, or no
  149. model exists with this name in the application. Raises ValueError if
  150. called with a single argument that doesn't contain exactly one dot.
  151. """
  152. if require_ready:
  153. self.check_models_ready()
  154. else:
  155. self.check_apps_ready()
  156. if model_name is None:
  157. app_label, model_name = app_label.split('.')
  158. app_config = self.get_app_config(app_label)
  159. if not require_ready and app_config.models is None:
  160. app_config.import_models()
  161. return app_config.get_model(model_name, require_ready=require_ready)
  162. def register_model(self, app_label, model):
  163. # Since this method is called when models are imported, it cannot
  164. # perform imports because of the risk of import loops. It mustn't
  165. # call get_app_config().
  166. model_name = model._meta.model_name
  167. app_models = self.all_models[app_label]
  168. if model_name in app_models:
  169. if (model.__name__ == app_models[model_name].__name__ and
  170. model.__module__ == app_models[model_name].__module__):
  171. warnings.warn(
  172. "Model '%s.%s' was already registered. "
  173. "Reloading models is not advised as it can lead to inconsistencies, "
  174. "most notably with related models." % (app_label, model_name),
  175. RuntimeWarning, stacklevel=2)
  176. else:
  177. raise RuntimeError(
  178. "Conflicting '%s' models in application '%s': %s and %s." %
  179. (model_name, app_label, app_models[model_name], model))
  180. app_models[model_name] = model
  181. self.do_pending_operations(model)
  182. self.clear_cache()
  183. def is_installed(self, app_name):
  184. """
  185. Checks whether an application with this name exists in the registry.
  186. app_name is the full name of the app eg. 'django.contrib.admin'.
  187. """
  188. self.check_apps_ready()
  189. return any(ac.name == app_name for ac in self.app_configs.values())
  190. def get_containing_app_config(self, object_name):
  191. """
  192. Look for an app config containing a given object.
  193. object_name is the dotted Python path to the object.
  194. Returns the app config for the inner application in case of nesting.
  195. Returns None if the object isn't in any registered app config.
  196. """
  197. self.check_apps_ready()
  198. candidates = []
  199. for app_config in self.app_configs.values():
  200. if object_name.startswith(app_config.name):
  201. subpath = object_name[len(app_config.name):]
  202. if subpath == '' or subpath[0] == '.':
  203. candidates.append(app_config)
  204. if candidates:
  205. return sorted(candidates, key=lambda ac: -len(ac.name))[0]
  206. def get_registered_model(self, app_label, model_name):
  207. """
  208. Similar to get_model(), but doesn't require that an app exists with
  209. the given app_label.
  210. It's safe to call this method at import time, even while the registry
  211. is being populated.
  212. """
  213. model = self.all_models[app_label].get(model_name.lower())
  214. if model is None:
  215. raise LookupError(
  216. "Model '%s.%s' not registered." % (app_label, model_name))
  217. return model
  218. @lru_cache.lru_cache(maxsize=None)
  219. def get_swappable_settings_name(self, to_string):
  220. """
  221. For a given model string (e.g. "auth.User"), return the name of the
  222. corresponding settings name if it refers to a swappable model. If the
  223. referred model is not swappable, return None.
  224. This method is decorated with lru_cache because it's performance
  225. critical when it comes to migrations. Since the swappable settings don't
  226. change after Django has loaded the settings, there is no reason to get
  227. the respective settings attribute over and over again.
  228. """
  229. for model in self.get_models(include_swapped=True):
  230. swapped = model._meta.swapped
  231. # Is this model swapped out for the model given by to_string?
  232. if swapped and swapped == to_string:
  233. return model._meta.swappable
  234. # Is this model swappable and the one given by to_string?
  235. if model._meta.swappable and model._meta.label == to_string:
  236. return model._meta.swappable
  237. return None
  238. def set_available_apps(self, available):
  239. """
  240. Restricts the set of installed apps used by get_app_config[s].
  241. available must be an iterable of application names.
  242. set_available_apps() must be balanced with unset_available_apps().
  243. Primarily used for performance optimization in TransactionTestCase.
  244. This method is safe is the sense that it doesn't trigger any imports.
  245. """
  246. available = set(available)
  247. installed = set(app_config.name for app_config in self.get_app_configs())
  248. if not available.issubset(installed):
  249. raise ValueError(
  250. "Available apps isn't a subset of installed apps, extra apps: %s"
  251. % ", ".join(available - installed)
  252. )
  253. self.stored_app_configs.append(self.app_configs)
  254. self.app_configs = OrderedDict(
  255. (label, app_config)
  256. for label, app_config in self.app_configs.items()
  257. if app_config.name in available)
  258. self.clear_cache()
  259. def unset_available_apps(self):
  260. """
  261. Cancels a previous call to set_available_apps().
  262. """
  263. self.app_configs = self.stored_app_configs.pop()
  264. self.clear_cache()
  265. def set_installed_apps(self, installed):
  266. """
  267. Enables a different set of installed apps for get_app_config[s].
  268. installed must be an iterable in the same format as INSTALLED_APPS.
  269. set_installed_apps() must be balanced with unset_installed_apps(),
  270. even if it exits with an exception.
  271. Primarily used as a receiver of the setting_changed signal in tests.
  272. This method may trigger new imports, which may add new models to the
  273. registry of all imported models. They will stay in the registry even
  274. after unset_installed_apps(). Since it isn't possible to replay
  275. imports safely (eg. that could lead to registering listeners twice),
  276. models are registered when they're imported and never removed.
  277. """
  278. if not self.ready:
  279. raise AppRegistryNotReady("App registry isn't ready yet.")
  280. self.stored_app_configs.append(self.app_configs)
  281. self.app_configs = OrderedDict()
  282. self.apps_ready = self.models_ready = self.ready = False
  283. self.clear_cache()
  284. self.populate(installed)
  285. def unset_installed_apps(self):
  286. """
  287. Cancels a previous call to set_installed_apps().
  288. """
  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. Clears 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[0], model_keys[1:]
  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)