Development of an internal social media platform with personalised dashboards for students
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

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