registry.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. from collections import defaultdict, OrderedDict
  2. import os
  3. import sys
  4. import warnings
  5. from django.core.exceptions import ImproperlyConfigured
  6. from django.utils import lru_cache
  7. from django.utils.module_loading import import_lock
  8. from django.utils._os import upath
  9. from .base import AppConfig
  10. class Apps(object):
  11. """
  12. A registry that stores the configuration of installed applications.
  13. It also keeps track of models eg. to provide reverse-relations.
  14. """
  15. def __init__(self, installed_apps=()):
  16. # installed_apps is set to None when creating the master registry
  17. # because it cannot be populated at that point. Other registries must
  18. # provide a list of installed apps and are populated immediately.
  19. if installed_apps is None and hasattr(sys.modules[__name__], 'apps'):
  20. raise RuntimeError("You must supply an installed_apps argument.")
  21. # Mapping of app labels => model names => model classes. Every time a
  22. # model is imported, ModelBase.__new__ calls apps.register_model which
  23. # creates an entry in all_models. All imported models are registered,
  24. # regardless of whether they're defined in an installed application
  25. # and whether the registry has been populated. Since it isn't possible
  26. # to reimport a module safely (it could reexecute initialization code)
  27. # all_models is never overridden or reset.
  28. self.all_models = defaultdict(OrderedDict)
  29. # Mapping of labels to AppConfig instances for installed apps.
  30. self.app_configs = OrderedDict()
  31. # Stack of app_configs. Used to store the current state in
  32. # set_available_apps and set_installed_apps.
  33. self.stored_app_configs = []
  34. # Whether the registry is populated.
  35. self.ready = False
  36. # Pending lookups for lazy relations.
  37. self._pending_lookups = {}
  38. # Populate apps and models, unless it's the master registry.
  39. if installed_apps is not None:
  40. self.populate(installed_apps)
  41. def populate(self, installed_apps=None):
  42. """
  43. Loads application configurations and models.
  44. This method imports each application module and then each model module.
  45. It is thread safe and idempotent, but not reentrant.
  46. """
  47. if self.ready:
  48. return
  49. # Since populate() may be a side effect of imports, and since it will
  50. # itself import modules, an ABBA deadlock between threads would be
  51. # possible if we didn't take the import lock. See #18251.
  52. with import_lock():
  53. if self.ready:
  54. return
  55. # app_config should be pristine, otherwise the code below won't
  56. # guarantee that the order matches the order in INSTALLED_APPS.
  57. if self.app_configs:
  58. raise RuntimeError("populate() isn't reentrant")
  59. # Load app configs and app modules.
  60. for entry in installed_apps:
  61. if isinstance(entry, AppConfig):
  62. app_config = entry
  63. else:
  64. app_config = AppConfig.create(entry)
  65. self.app_configs[app_config.label] = app_config
  66. # Load models.
  67. for app_config in self.app_configs.values():
  68. all_models = self.all_models[app_config.label]
  69. app_config.import_models(all_models)
  70. self.clear_cache()
  71. self.ready = True
  72. for app_config in self.get_app_configs():
  73. app_config.setup()
  74. def check_ready(self):
  75. """
  76. Raises an exception if the registry isn't ready.
  77. """
  78. if not self.ready:
  79. raise RuntimeError(
  80. "App registry isn't populated yet. "
  81. "Have you called django.setup()?")
  82. def get_app_configs(self):
  83. """
  84. Imports applications and returns an iterable of app configs.
  85. """
  86. self.check_ready()
  87. return self.app_configs.values()
  88. def get_app_config(self, app_label):
  89. """
  90. Imports applications and returns an app config for the given label.
  91. Raises LookupError if no application exists with this label.
  92. """
  93. self.check_ready()
  94. try:
  95. return self.app_configs[app_label]
  96. except KeyError:
  97. raise LookupError("No installed app with label '%s'." % app_label)
  98. # This method is performance-critical at least for Django's test suite.
  99. @lru_cache.lru_cache(maxsize=None)
  100. def get_models(self, app_mod=None, include_auto_created=False,
  101. include_deferred=False, include_swapped=False):
  102. """
  103. Returns a list of all installed models.
  104. By default, the following models aren't included:
  105. - auto-created models for many-to-many relations without
  106. an explicit intermediate table,
  107. - models created to satisfy deferred attribute queries,
  108. - models that have been swapped out.
  109. Set the corresponding keyword argument to True to include such models.
  110. """
  111. self.check_ready()
  112. if app_mod:
  113. warnings.warn(
  114. "The app_mod argument of get_models is deprecated.",
  115. PendingDeprecationWarning, stacklevel=2)
  116. app_label = app_mod.__name__.split('.')[-2]
  117. try:
  118. return list(self.get_app_config(app_label).get_models(
  119. include_auto_created, include_deferred, include_swapped))
  120. except LookupError:
  121. return []
  122. result = []
  123. for app_config in self.app_configs.values():
  124. result.extend(list(app_config.get_models(
  125. include_auto_created, include_deferred, include_swapped)))
  126. return result
  127. def get_model(self, app_label, model_name):
  128. """
  129. Returns the model matching the given app_label and model_name.
  130. model_name is case-insensitive.
  131. Raises LookupError if no application exists with this label, or no
  132. model exists with this name in the application.
  133. """
  134. self.check_ready()
  135. return self.get_app_config(app_label).get_model(model_name.lower())
  136. def register_model(self, app_label, model):
  137. # Since this method is called when models are imported, it cannot
  138. # perform imports because of the risk of import loops. It mustn't
  139. # call get_app_config().
  140. model_name = model._meta.model_name
  141. app_models = self.all_models[app_label]
  142. # Defensive check for extra safety.
  143. if model_name in app_models:
  144. raise RuntimeError(
  145. "Conflicting '%s' models in application '%s': %s and %s." %
  146. (model_name, app_label, app_models[model_name], model))
  147. app_models[model_name] = model
  148. self.clear_cache()
  149. def has_app(self, app_name):
  150. """
  151. Checks whether an application with this name exists in the registry.
  152. app_name is the full name of the app eg. 'django.contrib.admin'.
  153. It's safe to call this method at import time, even while the registry
  154. is being populated. It returns False for apps that aren't loaded yet.
  155. """
  156. app_config = self.app_configs.get(app_name.rpartition(".")[2])
  157. return app_config is not None and app_config.name == app_name
  158. def get_registered_model(self, app_label, model_name):
  159. """
  160. Similar to get_model(), but doesn't require that an app exists with
  161. the given app_label.
  162. It's safe to call this method at import time, even while the registry
  163. is being populated.
  164. """
  165. model = self.all_models[app_label].get(model_name.lower())
  166. if model is None:
  167. raise LookupError(
  168. "Model '%s.%s' not registered." % (app_label, model_name))
  169. return model
  170. def set_available_apps(self, available):
  171. """
  172. Restricts the set of installed apps used by get_app_config[s].
  173. available must be an iterable of application names.
  174. set_available_apps() must be balanced with unset_available_apps().
  175. Primarily used for performance optimization in TransactionTestCase.
  176. This method is safe is the sense that it doesn't trigger any imports.
  177. """
  178. available = set(available)
  179. installed = set(app_config.name for app_config in self.get_app_configs())
  180. if not available.issubset(installed):
  181. raise ValueError("Available apps isn't a subset of installed "
  182. "apps, extra apps: %s" % ", ".join(available - installed))
  183. self.stored_app_configs.append(self.app_configs)
  184. self.app_configs = OrderedDict(
  185. (label, app_config)
  186. for label, app_config in self.app_configs.items()
  187. if app_config.name in available)
  188. self.clear_cache()
  189. def unset_available_apps(self):
  190. """
  191. Cancels a previous call to set_available_apps().
  192. """
  193. self.app_configs = self.stored_app_configs.pop()
  194. self.clear_cache()
  195. def set_installed_apps(self, installed):
  196. """
  197. Enables a different set of installed apps for get_app_config[s].
  198. installed must be an iterable in the same format as INSTALLED_APPS.
  199. set_installed_apps() must be balanced with unset_installed_apps(),
  200. even if it exits with an exception.
  201. Primarily used as a receiver of the setting_changed signal in tests.
  202. This method may trigger new imports, which may add new models to the
  203. registry of all imported models. They will stay in the registry even
  204. after unset_installed_apps(). Since it isn't possible to replay
  205. imports safely (eg. that could lead to registering listeners twice),
  206. models are registered when they're imported and never removed.
  207. """
  208. self.check_ready()
  209. self.stored_app_configs.append(self.app_configs)
  210. self.app_configs = OrderedDict()
  211. self.ready = False
  212. self.clear_cache()
  213. self.populate(installed)
  214. def unset_installed_apps(self):
  215. """
  216. Cancels a previous call to set_installed_apps().
  217. """
  218. self.app_configs = self.stored_app_configs.pop()
  219. self.ready = True
  220. self.clear_cache()
  221. def clear_cache(self):
  222. """
  223. Clears all internal caches, for methods that alter the app registry.
  224. This is mostly used in tests.
  225. """
  226. self.get_models.cache_clear()
  227. ### DEPRECATED METHODS GO BELOW THIS LINE ###
  228. def load_app(self, app_name):
  229. """
  230. Loads the app with the provided fully qualified name, and returns the
  231. model module.
  232. """
  233. warnings.warn(
  234. "load_app(app_name) is deprecated.",
  235. PendingDeprecationWarning, stacklevel=2)
  236. app_config = AppConfig.create(app_name)
  237. app_config.import_models(self.all_models[app_config.label])
  238. self.app_configs[app_config.label] = app_config
  239. self.clear_cache()
  240. return app_config.models_module
  241. def app_cache_ready(self):
  242. warnings.warn(
  243. "app_cache_ready() is deprecated in favor of the ready property.",
  244. PendingDeprecationWarning, stacklevel=2)
  245. return self.ready
  246. def get_app(self, app_label):
  247. """
  248. Returns the module containing the models for the given app_label.
  249. """
  250. warnings.warn(
  251. "get_app_config(app_label).models_module supersedes get_app(app_label).",
  252. PendingDeprecationWarning, stacklevel=2)
  253. try:
  254. models_module = self.get_app_config(app_label).models_module
  255. except LookupError as exc:
  256. # Change the exception type for backwards compatibility.
  257. raise ImproperlyConfigured(*exc.args)
  258. if models_module is None:
  259. raise ImproperlyConfigured(
  260. "App '%s' doesn't have a models module." % app_label)
  261. return models_module
  262. def get_apps(self):
  263. """
  264. Returns a list of all installed modules that contain models.
  265. """
  266. warnings.warn(
  267. "[a.models_module for a in get_app_configs()] supersedes get_apps().",
  268. PendingDeprecationWarning, stacklevel=2)
  269. app_configs = self.get_app_configs()
  270. return [app_config.models_module for app_config in app_configs
  271. if app_config.models_module is not None]
  272. def _get_app_package(self, app):
  273. return '.'.join(app.__name__.split('.')[:-1])
  274. def get_app_package(self, app_label):
  275. warnings.warn(
  276. "get_app_config(label).name supersedes get_app_package(label).",
  277. PendingDeprecationWarning, stacklevel=2)
  278. return self._get_app_package(self.get_app(app_label))
  279. def _get_app_path(self, app):
  280. if hasattr(app, '__path__'): # models/__init__.py package
  281. app_path = app.__path__[0]
  282. else: # models.py module
  283. app_path = app.__file__
  284. return os.path.dirname(upath(app_path))
  285. def get_app_path(self, app_label):
  286. warnings.warn(
  287. "get_app_config(label).path supersedes get_app_path(label).",
  288. PendingDeprecationWarning, stacklevel=2)
  289. return self._get_app_path(self.get_app(app_label))
  290. def get_app_paths(self):
  291. """
  292. Returns a list of paths to all installed apps.
  293. Useful for discovering files at conventional locations inside apps
  294. (static files, templates, etc.)
  295. """
  296. warnings.warn(
  297. "[a.path for a in get_app_configs()] supersedes get_app_paths().",
  298. PendingDeprecationWarning, stacklevel=2)
  299. self.check_ready()
  300. app_paths = []
  301. for app in self.get_apps():
  302. app_paths.append(self._get_app_path(app))
  303. return app_paths
  304. def register_models(self, app_label, *models):
  305. """
  306. Register a set of models as belonging to an app.
  307. """
  308. warnings.warn(
  309. "register_models(app_label, *models) is deprecated.",
  310. PendingDeprecationWarning, stacklevel=2)
  311. for model in models:
  312. self.register_model(app_label, model)
  313. apps = Apps(installed_apps=None)