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.
 
 
 
 

409 lines
16 KiB

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