2017-01-19 04:30:21 +08:00
|
|
|
import functools
|
2013-12-12 04:44:27 +08:00
|
|
|
import sys
|
2014-01-13 05:04:22 +08:00
|
|
|
import threading
|
2013-12-14 02:28:42 +08:00
|
|
|
import warnings
|
2019-02-05 19:22:08 +08:00
|
|
|
from collections import Counter, defaultdict
|
2015-03-03 16:43:56 +08:00
|
|
|
from functools import partial
|
2013-12-12 04:44:27 +08:00
|
|
|
|
2014-06-21 21:00:35 +08:00
|
|
|
from django.core.exceptions import AppRegistryNotReady, ImproperlyConfigured
|
2013-12-12 04:44:27 +08:00
|
|
|
|
2014-01-26 20:17:03 +08:00
|
|
|
from .config import AppConfig
|
2013-12-12 04:44:27 +08:00
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class Apps:
|
2013-12-12 04:44:27 +08:00
|
|
|
"""
|
2013-12-24 19:25:17 +08:00
|
|
|
A registry that stores the configuration of installed applications.
|
|
|
|
|
2017-01-25 04:37:33 +08:00
|
|
|
It also keeps track of models, e.g. to provide reverse relations.
|
2013-12-12 04:44:27 +08:00
|
|
|
"""
|
2013-12-18 00:47:19 +08:00
|
|
|
|
2013-12-30 23:03:06 +08:00
|
|
|
def __init__(self, installed_apps=()):
|
|
|
|
# installed_apps is set to None when creating the master registry
|
|
|
|
# because it cannot be populated at that point. Other registries must
|
|
|
|
# provide a list of installed apps and are populated immediately.
|
|
|
|
if installed_apps is None and hasattr(sys.modules[__name__], 'apps'):
|
|
|
|
raise RuntimeError("You must supply an installed_apps argument.")
|
2013-12-18 00:47:19 +08:00
|
|
|
|
2013-12-26 21:12:30 +08:00
|
|
|
# Mapping of app labels => model names => model classes. Every time a
|
|
|
|
# model is imported, ModelBase.__new__ calls apps.register_model which
|
|
|
|
# creates an entry in all_models. All imported models are registered,
|
|
|
|
# regardless of whether they're defined in an installed application
|
|
|
|
# and whether the registry has been populated. Since it isn't possible
|
|
|
|
# to reimport a module safely (it could reexecute initialization code)
|
|
|
|
# all_models is never overridden or reset.
|
2019-02-05 19:22:08 +08:00
|
|
|
self.all_models = defaultdict(dict)
|
2013-12-18 18:19:56 +08:00
|
|
|
|
2013-12-12 18:28:04 +08:00
|
|
|
# Mapping of labels to AppConfig instances for installed apps.
|
2019-02-05 19:22:08 +08:00
|
|
|
self.app_configs = {}
|
2013-12-12 04:44:27 +08:00
|
|
|
|
2013-12-23 07:10:53 +08:00
|
|
|
# Stack of app_configs. Used to store the current state in
|
|
|
|
# set_available_apps and set_installed_apps.
|
|
|
|
self.stored_app_configs = []
|
2013-12-12 04:44:27 +08:00
|
|
|
|
2013-12-31 06:15:29 +08:00
|
|
|
# Whether the registry is populated.
|
2014-07-12 21:33:21 +08:00
|
|
|
self.apps_ready = self.models_ready = self.ready = False
|
2019-01-14 09:33:47 +08:00
|
|
|
# For the autoreloader.
|
|
|
|
self.ready_event = threading.Event()
|
2013-12-18 18:28:21 +08:00
|
|
|
|
2014-01-13 05:04:22 +08:00
|
|
|
# Lock for thread-safe population.
|
2017-02-26 04:56:24 +08:00
|
|
|
self._lock = threading.RLock()
|
|
|
|
self.loading = False
|
2014-01-13 05:04:22 +08:00
|
|
|
|
2015-03-03 16:43:56 +08:00
|
|
|
# Maps ("app_label", "modelname") tuples to lists of functions to be
|
|
|
|
# called when the corresponding model is ready. Used by this class's
|
|
|
|
# `lazy_model_operation()` and `do_pending_operations()` methods.
|
|
|
|
self._pending_operations = defaultdict(list)
|
2013-12-18 23:49:42 +08:00
|
|
|
|
2013-12-30 23:03:06 +08:00
|
|
|
# Populate apps and models, unless it's the master registry.
|
|
|
|
if installed_apps is not None:
|
2013-12-31 06:15:29 +08:00
|
|
|
self.populate(installed_apps)
|
2013-12-30 23:03:06 +08:00
|
|
|
|
2013-12-31 06:15:29 +08:00
|
|
|
def populate(self, installed_apps=None):
|
2013-12-18 18:28:21 +08:00
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Load application configurations and models.
|
2013-12-18 18:28:21 +08:00
|
|
|
|
2017-01-25 04:37:33 +08:00
|
|
|
Import each application module and then each model module.
|
2013-12-18 18:28:21 +08:00
|
|
|
|
2017-01-25 04:37:33 +08:00
|
|
|
It is thread-safe and idempotent, but not reentrant.
|
2013-12-18 18:28:21 +08:00
|
|
|
"""
|
2013-12-31 06:15:29 +08:00
|
|
|
if self.ready:
|
2013-12-18 18:28:21 +08:00
|
|
|
return
|
2014-01-13 05:04:22 +08:00
|
|
|
|
|
|
|
# populate() might be called by two threads in parallel on servers
|
|
|
|
# that create threads before initializing the WSGI callable.
|
|
|
|
with self._lock:
|
2013-12-31 06:15:29 +08:00
|
|
|
if self.ready:
|
2013-12-18 18:28:21 +08:00
|
|
|
return
|
|
|
|
|
2017-02-26 04:56:24 +08:00
|
|
|
# An RLock prevents other threads from entering this section. The
|
|
|
|
# compare and set operation below is atomic.
|
|
|
|
if self.loading:
|
|
|
|
# Prevent reentrant calls to avoid running AppConfig.ready()
|
|
|
|
# methods twice.
|
2013-12-31 06:15:29 +08:00
|
|
|
raise RuntimeError("populate() isn't reentrant")
|
2017-02-26 04:56:24 +08:00
|
|
|
self.loading = True
|
2013-12-18 18:28:21 +08:00
|
|
|
|
2016-10-01 03:35:04 +08:00
|
|
|
# Phase 1: initialize app configs and import app modules.
|
2013-12-29 03:13:08 +08:00
|
|
|
for entry in installed_apps:
|
|
|
|
if isinstance(entry, AppConfig):
|
|
|
|
app_config = entry
|
|
|
|
else:
|
|
|
|
app_config = AppConfig.create(entry)
|
2014-01-01 00:25:57 +08:00
|
|
|
if app_config.label in self.app_configs:
|
|
|
|
raise ImproperlyConfigured(
|
|
|
|
"Application labels aren't unique, "
|
|
|
|
"duplicates: %s" % app_config.label)
|
|
|
|
|
2013-12-18 18:28:21 +08:00
|
|
|
self.app_configs[app_config.label] = app_config
|
2016-10-01 03:08:35 +08:00
|
|
|
app_config.apps = self
|
2013-12-18 18:28:21 +08:00
|
|
|
|
2013-12-31 23:22:42 +08:00
|
|
|
# Check for duplicate app names.
|
|
|
|
counts = Counter(
|
|
|
|
app_config.name for app_config in self.app_configs.values())
|
|
|
|
duplicates = [
|
|
|
|
name for name, count in counts.most_common() if count > 1]
|
|
|
|
if duplicates:
|
|
|
|
raise ImproperlyConfigured(
|
|
|
|
"Application names aren't unique, "
|
|
|
|
"duplicates: %s" % ", ".join(duplicates))
|
|
|
|
|
2014-07-12 21:33:21 +08:00
|
|
|
self.apps_ready = True
|
|
|
|
|
2016-10-01 03:35:04 +08:00
|
|
|
# Phase 2: import models modules.
|
2013-12-18 18:28:21 +08:00
|
|
|
for app_config in self.app_configs.values():
|
2016-10-01 03:35:04 +08:00
|
|
|
app_config.import_models()
|
2013-12-18 18:28:21 +08:00
|
|
|
|
2013-12-31 06:01:00 +08:00
|
|
|
self.clear_cache()
|
2014-07-12 21:33:21 +08:00
|
|
|
|
|
|
|
self.models_ready = True
|
2013-12-18 18:28:21 +08:00
|
|
|
|
2016-10-01 03:35:04 +08:00
|
|
|
# Phase 3: run ready() methods of app configs.
|
2013-12-31 06:01:00 +08:00
|
|
|
for app_config in self.get_app_configs():
|
2014-01-01 00:55:12 +08:00
|
|
|
app_config.ready()
|
2013-12-30 19:49:53 +08:00
|
|
|
|
2014-07-12 21:33:21 +08:00
|
|
|
self.ready = True
|
2019-01-14 09:33:47 +08:00
|
|
|
self.ready_event.set()
|
2014-07-12 21:33:21 +08:00
|
|
|
|
|
|
|
def check_apps_ready(self):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""Raise an exception if all apps haven't been imported yet."""
|
2014-07-12 21:33:21 +08:00
|
|
|
if not self.apps_ready:
|
2013-02-04 21:35:52 +08:00
|
|
|
from django.conf import settings
|
2020-07-24 14:25:47 +08:00
|
|
|
|
2013-02-04 21:35:52 +08:00
|
|
|
# If "not ready" is due to unconfigured settings, accessing
|
|
|
|
# INSTALLED_APPS raises a more helpful ImproperlyConfigured
|
|
|
|
# exception.
|
|
|
|
settings.INSTALLED_APPS
|
2014-07-12 21:33:21 +08:00
|
|
|
raise AppRegistryNotReady("Apps aren't loaded yet.")
|
|
|
|
|
|
|
|
def check_models_ready(self):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""Raise an exception if all models haven't been imported yet."""
|
2014-07-12 21:33:21 +08:00
|
|
|
if not self.models_ready:
|
2014-10-05 01:13:54 +08:00
|
|
|
raise AppRegistryNotReady("Models aren't loaded yet.")
|
2013-12-30 22:42:15 +08:00
|
|
|
|
2013-12-31 06:53:54 +08:00
|
|
|
def get_app_configs(self):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""Import applications and return an iterable of app configs."""
|
2014-07-12 21:33:21 +08:00
|
|
|
self.check_apps_ready()
|
2013-12-31 06:53:54 +08:00
|
|
|
return self.app_configs.values()
|
2013-12-14 03:22:21 +08:00
|
|
|
|
2013-12-31 06:53:54 +08:00
|
|
|
def get_app_config(self, app_label):
|
Added get_app_config() to look up app configs by label.
Refactored get_app() to rely on that method.
get_app() starts by calling _populate(), which goes through
INSTALLED_APPS and, for each app, imports the app module and attempts to
import the models module. At this point, no further imports are
necessary to return the models module for a given app. Therefore, the
implementation of get_app() can be simplified and the safeguards for
race conditions can be removed.
Besides, the emptyOK parameter isn't used anywhere in Django. It was
introduced in d6c95e93 but not actually used nor documented, and it has
just been carried around since then. Since it's an obscure private API,
it's acceptable to stop supporting it without a deprecation path. This
branch aims at providing first-class support for applications without a
models module eventually.
For backwards-compatibility, get_app() still raises ImproperlyConfigured
when an app isn't found, even though LookupError is technically more
correct. I haven't gone as far as to preserve the exact error messages.
I've adjusted a few tests instead.
2013-12-13 19:02:54 +08:00
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Import applications and returns an app config for the given label.
|
Added get_app_config() to look up app configs by label.
Refactored get_app() to rely on that method.
get_app() starts by calling _populate(), which goes through
INSTALLED_APPS and, for each app, imports the app module and attempts to
import the models module. At this point, no further imports are
necessary to return the models module for a given app. Therefore, the
implementation of get_app() can be simplified and the safeguards for
race conditions can be removed.
Besides, the emptyOK parameter isn't used anywhere in Django. It was
introduced in d6c95e93 but not actually used nor documented, and it has
just been carried around since then. Since it's an obscure private API,
it's acceptable to stop supporting it without a deprecation path. This
branch aims at providing first-class support for applications without a
models module eventually.
For backwards-compatibility, get_app() still raises ImproperlyConfigured
when an app isn't found, even though LookupError is technically more
correct. I haven't gone as far as to preserve the exact error messages.
I've adjusted a few tests instead.
2013-12-13 19:02:54 +08:00
|
|
|
|
2017-01-25 04:37:33 +08:00
|
|
|
Raise LookupError if no application exists with this label.
|
Added get_app_config() to look up app configs by label.
Refactored get_app() to rely on that method.
get_app() starts by calling _populate(), which goes through
INSTALLED_APPS and, for each app, imports the app module and attempts to
import the models module. At this point, no further imports are
necessary to return the models module for a given app. Therefore, the
implementation of get_app() can be simplified and the safeguards for
race conditions can be removed.
Besides, the emptyOK parameter isn't used anywhere in Django. It was
introduced in d6c95e93 but not actually used nor documented, and it has
just been carried around since then. Since it's an obscure private API,
it's acceptable to stop supporting it without a deprecation path. This
branch aims at providing first-class support for applications without a
models module eventually.
For backwards-compatibility, get_app() still raises ImproperlyConfigured
when an app isn't found, even though LookupError is technically more
correct. I haven't gone as far as to preserve the exact error messages.
I've adjusted a few tests instead.
2013-12-13 19:02:54 +08:00
|
|
|
"""
|
2014-07-12 21:33:21 +08:00
|
|
|
self.check_apps_ready()
|
2013-12-31 06:53:54 +08:00
|
|
|
try:
|
|
|
|
return self.app_configs[app_label]
|
|
|
|
except KeyError:
|
2015-05-12 17:02:23 +08:00
|
|
|
message = "No installed app with label '%s'." % app_label
|
|
|
|
for app_config in self.get_app_configs():
|
|
|
|
if app_config.name == app_label:
|
|
|
|
message += " Did you mean '%s'?" % app_config.label
|
|
|
|
break
|
|
|
|
raise LookupError(message)
|
Added get_app_config() to look up app configs by label.
Refactored get_app() to rely on that method.
get_app() starts by calling _populate(), which goes through
INSTALLED_APPS and, for each app, imports the app module and attempts to
import the models module. At this point, no further imports are
necessary to return the models module for a given app. Therefore, the
implementation of get_app() can be simplified and the safeguards for
race conditions can be removed.
Besides, the emptyOK parameter isn't used anywhere in Django. It was
introduced in d6c95e93 but not actually used nor documented, and it has
just been carried around since then. Since it's an obscure private API,
it's acceptable to stop supporting it without a deprecation path. This
branch aims at providing first-class support for applications without a
models module eventually.
For backwards-compatibility, get_app() still raises ImproperlyConfigured
when an app isn't found, even though LookupError is technically more
correct. I haven't gone as far as to preserve the exact error messages.
I've adjusted a few tests instead.
2013-12-13 19:02:54 +08:00
|
|
|
|
2013-12-24 17:08:04 +08:00
|
|
|
# This method is performance-critical at least for Django's test suite.
|
2017-01-19 04:30:21 +08:00
|
|
|
@functools.lru_cache(maxsize=None)
|
2016-02-02 17:33:09 +08:00
|
|
|
def get_models(self, include_auto_created=False, include_swapped=False):
|
2013-12-12 04:44:27 +08:00
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Return a list of all installed models.
|
2013-12-12 04:44:27 +08:00
|
|
|
|
2013-12-30 04:47:55 +08:00
|
|
|
By default, the following models aren't included:
|
2013-12-12 04:44:27 +08:00
|
|
|
|
2013-12-30 04:47:55 +08:00
|
|
|
- auto-created models for many-to-many relations without
|
|
|
|
an explicit intermediate table,
|
|
|
|
- models that have been swapped out.
|
2013-12-12 04:44:27 +08:00
|
|
|
|
2013-12-30 04:47:55 +08:00
|
|
|
Set the corresponding keyword argument to True to include such models.
|
2013-12-12 04:44:27 +08:00
|
|
|
"""
|
2014-07-12 21:33:21 +08:00
|
|
|
self.check_models_ready()
|
2013-12-30 04:47:55 +08:00
|
|
|
|
|
|
|
result = []
|
|
|
|
for app_config in self.app_configs.values():
|
2018-09-25 23:30:43 +08:00
|
|
|
result.extend(app_config.get_models(include_auto_created, include_swapped))
|
2013-12-30 04:47:55 +08:00
|
|
|
return result
|
2013-12-12 04:44:27 +08:00
|
|
|
|
2016-05-03 18:21:54 +08:00
|
|
|
def get_model(self, app_label, model_name=None, require_ready=True):
|
2013-12-12 04:44:27 +08:00
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Return the model matching the given app_label and model_name.
|
2013-12-12 04:44:27 +08:00
|
|
|
|
2017-01-25 04:37:33 +08:00
|
|
|
As a shortcut, app_label may be in the form <app_label>.<model_name>.
|
2014-01-26 19:46:28 +08:00
|
|
|
|
2013-12-28 21:41:11 +08:00
|
|
|
model_name is case-insensitive.
|
|
|
|
|
2017-01-25 04:37:33 +08:00
|
|
|
Raise LookupError if no application exists with this label, or no
|
|
|
|
model exists with this name in the application. Raise ValueError if
|
2014-01-26 19:46:28 +08:00
|
|
|
called with a single argument that doesn't contain exactly one dot.
|
2013-12-12 04:44:27 +08:00
|
|
|
"""
|
2016-05-03 18:21:54 +08:00
|
|
|
if require_ready:
|
|
|
|
self.check_models_ready()
|
|
|
|
else:
|
|
|
|
self.check_apps_ready()
|
|
|
|
|
2014-01-26 19:46:28 +08:00
|
|
|
if model_name is None:
|
|
|
|
app_label, model_name = app_label.split('.')
|
2016-05-03 18:21:54 +08:00
|
|
|
|
|
|
|
app_config = self.get_app_config(app_label)
|
|
|
|
|
|
|
|
if not require_ready and app_config.models is None:
|
|
|
|
app_config.import_models()
|
|
|
|
|
|
|
|
return app_config.get_model(model_name, require_ready=require_ready)
|
2013-12-12 04:44:27 +08:00
|
|
|
|
2013-12-14 04:29:30 +08:00
|
|
|
def register_model(self, app_label, model):
|
2013-12-18 18:19:56 +08:00
|
|
|
# Since this method is called when models are imported, it cannot
|
|
|
|
# perform imports because of the risk of import loops. It mustn't
|
|
|
|
# call get_app_config().
|
2013-12-14 04:29:30 +08:00
|
|
|
model_name = model._meta.model_name
|
Simplified the implementation of register_model.
register_model is called exactly once in the entire Django code base, at the
bottom of ModelBase.__new__:
new_class._meta.apps.register_model(new_class._meta.app_label, new_class)
ModelBase.__new__ exits prematurely 120 lines earlier (sigh) if a model with
the same name is already registered:
if new_class._meta.apps.get_registered_model(new_class._meta.app_label, name):
return
(This isn't the exact code, but it's equivalent.)
apps.register_model and apps.get_registered_model are essentially a setter and
a getter for apps.all_models, and apps.register_model is the only setter. As a
consequence, new_class._meta.apps.all_models cannot change in-between.
Considering that name == new_class.__name__, we can conclude that
register_model(app_label, model) is always called with such arguments that
get_registered_model(app_label, model.__name__) returns None.
Considering that model._meta.model_name == model.__name__.lower(), and looking
at the implementation of register_model and get_registered_model, this proves
that self.all_models[app_label] doesn't contain model._meta.model_name in
register_model, allowing us to simplify the implementation.
2013-12-28 06:03:03 +08:00
|
|
|
app_models = self.all_models[app_label]
|
|
|
|
if model_name in app_models:
|
2014-10-23 00:16:32 +08:00
|
|
|
if (model.__name__ == app_models[model_name].__name__ and
|
|
|
|
model.__module__ == app_models[model_name].__module__):
|
|
|
|
warnings.warn(
|
2014-10-23 02:28:57 +08:00
|
|
|
"Model '%s.%s' was already registered. "
|
|
|
|
"Reloading models is not advised as it can lead to inconsistencies, "
|
2015-07-01 02:38:07 +08:00
|
|
|
"most notably with related models." % (app_label, model_name),
|
2014-10-23 00:16:32 +08:00
|
|
|
RuntimeWarning, stacklevel=2)
|
|
|
|
else:
|
|
|
|
raise RuntimeError(
|
|
|
|
"Conflicting '%s' models in application '%s': %s and %s." %
|
|
|
|
(model_name, app_label, app_models[model_name], model))
|
Simplified the implementation of register_model.
register_model is called exactly once in the entire Django code base, at the
bottom of ModelBase.__new__:
new_class._meta.apps.register_model(new_class._meta.app_label, new_class)
ModelBase.__new__ exits prematurely 120 lines earlier (sigh) if a model with
the same name is already registered:
if new_class._meta.apps.get_registered_model(new_class._meta.app_label, name):
return
(This isn't the exact code, but it's equivalent.)
apps.register_model and apps.get_registered_model are essentially a setter and
a getter for apps.all_models, and apps.register_model is the only setter. As a
consequence, new_class._meta.apps.all_models cannot change in-between.
Considering that name == new_class.__name__, we can conclude that
register_model(app_label, model) is always called with such arguments that
get_registered_model(app_label, model.__name__) returns None.
Considering that model._meta.model_name == model.__name__.lower(), and looking
at the implementation of register_model and get_registered_model, this proves
that self.all_models[app_label] doesn't contain model._meta.model_name in
register_model, allowing us to simplify the implementation.
2013-12-28 06:03:03 +08:00
|
|
|
app_models[model_name] = model
|
2015-03-03 16:43:56 +08:00
|
|
|
self.do_pending_operations(model)
|
2013-12-30 03:43:10 +08:00
|
|
|
self.clear_cache()
|
2013-12-12 04:44:27 +08:00
|
|
|
|
2014-01-07 05:48:41 +08:00
|
|
|
def is_installed(self, app_name):
|
2013-12-20 04:57:09 +08:00
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Check whether an application with this name exists in the registry.
|
2013-12-23 00:07:18 +08:00
|
|
|
|
2017-01-25 04:37:33 +08:00
|
|
|
app_name is the full name of the app e.g. 'django.contrib.admin'.
|
2013-12-20 04:57:09 +08:00
|
|
|
"""
|
2014-07-12 21:33:21 +08:00
|
|
|
self.check_apps_ready()
|
2014-01-25 11:07:14 +08:00
|
|
|
return any(ac.name == app_name for ac in self.app_configs.values())
|
2013-12-20 04:57:09 +08:00
|
|
|
|
2013-12-31 23:23:42 +08:00
|
|
|
def get_containing_app_config(self, object_name):
|
|
|
|
"""
|
|
|
|
Look for an app config containing a given object.
|
|
|
|
|
|
|
|
object_name is the dotted Python path to the object.
|
|
|
|
|
2017-01-25 04:37:33 +08:00
|
|
|
Return the app config for the inner application in case of nesting.
|
|
|
|
Return None if the object isn't in any registered app config.
|
2013-12-31 23:23:42 +08:00
|
|
|
"""
|
2015-02-09 02:38:09 +08:00
|
|
|
self.check_apps_ready()
|
2013-12-31 23:23:42 +08:00
|
|
|
candidates = []
|
|
|
|
for app_config in self.app_configs.values():
|
|
|
|
if object_name.startswith(app_config.name):
|
|
|
|
subpath = object_name[len(app_config.name):]
|
|
|
|
if subpath == '' or subpath[0] == '.':
|
|
|
|
candidates.append(app_config)
|
|
|
|
if candidates:
|
|
|
|
return sorted(candidates, key=lambda ac: -len(ac.name))[0]
|
|
|
|
|
2013-12-23 00:07:52 +08:00
|
|
|
def get_registered_model(self, app_label, model_name):
|
2013-12-18 18:19:56 +08:00
|
|
|
"""
|
2013-12-28 21:41:11 +08:00
|
|
|
Similar to get_model(), but doesn't require that an app exists with
|
|
|
|
the given app_label.
|
2013-12-18 18:19:56 +08:00
|
|
|
|
2013-12-24 19:25:17 +08:00
|
|
|
It's safe to call this method at import time, even while the registry
|
2013-12-28 21:55:54 +08:00
|
|
|
is being populated.
|
2013-12-18 18:19:56 +08:00
|
|
|
"""
|
2013-12-28 21:55:54 +08:00
|
|
|
model = self.all_models[app_label].get(model_name.lower())
|
|
|
|
if model is None:
|
|
|
|
raise LookupError(
|
|
|
|
"Model '%s.%s' not registered." % (app_label, model_name))
|
|
|
|
return model
|
2013-12-18 18:19:56 +08:00
|
|
|
|
2017-01-19 04:30:21 +08:00
|
|
|
@functools.lru_cache(maxsize=None)
|
2015-08-22 21:40:34 +08:00
|
|
|
def get_swappable_settings_name(self, to_string):
|
|
|
|
"""
|
|
|
|
For a given model string (e.g. "auth.User"), return the name of the
|
|
|
|
corresponding settings name if it refers to a swappable model. If the
|
|
|
|
referred model is not swappable, return None.
|
|
|
|
|
|
|
|
This method is decorated with lru_cache because it's performance
|
|
|
|
critical when it comes to migrations. Since the swappable settings don't
|
|
|
|
change after Django has loaded the settings, there is no reason to get
|
|
|
|
the respective settings attribute over and over again.
|
|
|
|
"""
|
2021-12-16 08:36:08 +08:00
|
|
|
to_string = to_string.lower()
|
2015-08-22 21:40:34 +08:00
|
|
|
for model in self.get_models(include_swapped=True):
|
|
|
|
swapped = model._meta.swapped
|
|
|
|
# Is this model swapped out for the model given by to_string?
|
2021-12-16 08:36:08 +08:00
|
|
|
if swapped and swapped.lower() == to_string:
|
2015-08-22 21:40:34 +08:00
|
|
|
return model._meta.swappable
|
|
|
|
# Is this model swappable and the one given by to_string?
|
2021-12-16 08:36:08 +08:00
|
|
|
if model._meta.swappable and model._meta.label_lower == to_string:
|
2015-08-22 21:40:34 +08:00
|
|
|
return model._meta.swappable
|
|
|
|
return None
|
|
|
|
|
2013-12-12 04:44:27 +08:00
|
|
|
def set_available_apps(self, available):
|
2013-12-20 17:39:12 +08:00
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Restrict the set of installed apps used by get_app_config[s].
|
2013-12-20 17:39:12 +08:00
|
|
|
|
|
|
|
available must be an iterable of application names.
|
|
|
|
|
2013-12-24 07:07:54 +08:00
|
|
|
set_available_apps() must be balanced with unset_available_apps().
|
|
|
|
|
2013-12-20 17:39:12 +08:00
|
|
|
Primarily used for performance optimization in TransactionTestCase.
|
2013-12-23 07:10:53 +08:00
|
|
|
|
2017-01-25 04:37:33 +08:00
|
|
|
This method is safe in the sense that it doesn't trigger any imports.
|
2013-12-20 17:39:12 +08:00
|
|
|
"""
|
2013-12-14 03:51:21 +08:00
|
|
|
available = set(available)
|
2017-06-02 07:08:59 +08:00
|
|
|
installed = {app_config.name for app_config in self.get_app_configs()}
|
2013-12-14 03:51:21 +08:00
|
|
|
if not available.issubset(installed):
|
2016-03-29 06:33:29 +08:00
|
|
|
raise ValueError(
|
|
|
|
"Available apps isn't a subset of installed apps, extra apps: %s"
|
|
|
|
% ", ".join(available - installed)
|
|
|
|
)
|
2013-12-23 07:10:53 +08:00
|
|
|
|
|
|
|
self.stored_app_configs.append(self.app_configs)
|
2019-02-05 19:22:08 +08:00
|
|
|
self.app_configs = {
|
|
|
|
label: app_config
|
2013-12-23 07:10:53 +08:00
|
|
|
for label, app_config in self.app_configs.items()
|
2019-02-05 19:22:08 +08:00
|
|
|
if app_config.name in available
|
|
|
|
}
|
2013-12-30 03:43:10 +08:00
|
|
|
self.clear_cache()
|
2013-12-12 04:44:27 +08:00
|
|
|
|
|
|
|
def unset_available_apps(self):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""Cancel a previous call to set_available_apps()."""
|
2013-12-23 07:10:53 +08:00
|
|
|
self.app_configs = self.stored_app_configs.pop()
|
2013-12-30 03:43:10 +08:00
|
|
|
self.clear_cache()
|
2013-12-23 07:10:53 +08:00
|
|
|
|
|
|
|
def set_installed_apps(self, installed):
|
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Enable a different set of installed apps for get_app_config[s].
|
2013-12-23 07:10:53 +08:00
|
|
|
|
|
|
|
installed must be an iterable in the same format as INSTALLED_APPS.
|
|
|
|
|
2013-12-24 07:07:54 +08:00
|
|
|
set_installed_apps() must be balanced with unset_installed_apps(),
|
|
|
|
even if it exits with an exception.
|
|
|
|
|
2013-12-23 07:10:53 +08:00
|
|
|
Primarily used as a receiver of the setting_changed signal in tests.
|
|
|
|
|
|
|
|
This method may trigger new imports, which may add new models to the
|
|
|
|
registry of all imported models. They will stay in the registry even
|
|
|
|
after unset_installed_apps(). Since it isn't possible to replay
|
2017-01-25 04:37:33 +08:00
|
|
|
imports safely (e.g. that could lead to registering listeners twice),
|
2013-12-23 07:10:53 +08:00
|
|
|
models are registered when they're imported and never removed.
|
|
|
|
"""
|
2014-07-12 21:33:21 +08:00
|
|
|
if not self.ready:
|
|
|
|
raise AppRegistryNotReady("App registry isn't ready yet.")
|
2013-12-30 22:42:15 +08:00
|
|
|
self.stored_app_configs.append(self.app_configs)
|
2019-02-05 19:22:08 +08:00
|
|
|
self.app_configs = {}
|
2017-02-26 04:56:24 +08:00
|
|
|
self.apps_ready = self.models_ready = self.loading = self.ready = False
|
2013-12-30 03:43:10 +08:00
|
|
|
self.clear_cache()
|
2013-12-31 06:15:29 +08:00
|
|
|
self.populate(installed)
|
2013-12-23 07:10:53 +08:00
|
|
|
|
|
|
|
def unset_installed_apps(self):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""Cancel a previous call to set_installed_apps()."""
|
2013-12-30 22:42:15 +08:00
|
|
|
self.app_configs = self.stored_app_configs.pop()
|
2014-07-12 21:33:21 +08:00
|
|
|
self.apps_ready = self.models_ready = self.ready = True
|
2013-12-30 03:43:10 +08:00
|
|
|
self.clear_cache()
|
|
|
|
|
|
|
|
def clear_cache(self):
|
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Clear all internal caches, for methods that alter the app registry.
|
2013-12-30 03:43:10 +08:00
|
|
|
|
|
|
|
This is mostly used in tests.
|
|
|
|
"""
|
2015-01-07 08:16:35 +08:00
|
|
|
# Call expire cache on each model. This will purge
|
|
|
|
# the relation tree and the fields cache.
|
2013-12-30 03:57:03 +08:00
|
|
|
self.get_models.cache_clear()
|
2015-01-07 08:16:35 +08:00
|
|
|
if self.ready:
|
2015-02-22 11:26:17 +08:00
|
|
|
# Circumvent self.get_models() to prevent that the cache is refilled.
|
|
|
|
# This particularly prevents that an empty value is cached while cloning.
|
|
|
|
for app_config in self.app_configs.values():
|
|
|
|
for model in app_config.get_models(include_auto_created=True):
|
|
|
|
model._meta._expire_cache()
|
2013-12-12 04:44:27 +08:00
|
|
|
|
2015-03-03 16:43:56 +08:00
|
|
|
def lazy_model_operation(self, function, *model_keys):
|
|
|
|
"""
|
|
|
|
Take a function and a number of ("app_label", "modelname") tuples, and
|
|
|
|
when all the corresponding models have been imported and registered,
|
|
|
|
call the function with the model classes as its arguments.
|
|
|
|
|
|
|
|
The function passed to this method must accept exactly n models as
|
|
|
|
arguments, where n=len(model_keys).
|
|
|
|
"""
|
2016-05-18 23:18:40 +08:00
|
|
|
# Base case: no arguments, just execute the function.
|
|
|
|
if not model_keys:
|
|
|
|
function()
|
|
|
|
# Recursive case: take the head of model_keys, wait for the
|
|
|
|
# corresponding model class to be imported and registered, then apply
|
|
|
|
# that argument to the supplied function. Pass the resulting partial
|
|
|
|
# to lazy_model_operation() along with the remaining model args and
|
|
|
|
# repeat until all models are loaded and all arguments are applied.
|
2015-03-03 16:43:56 +08:00
|
|
|
else:
|
2018-09-28 21:57:12 +08:00
|
|
|
next_model, *more_models = model_keys
|
2016-05-18 23:18:40 +08:00
|
|
|
|
|
|
|
# This will be executed after the class corresponding to next_model
|
|
|
|
# has been imported and registered. The `func` attribute provides
|
|
|
|
# duck-type compatibility with partials.
|
|
|
|
def apply_next_model(model):
|
|
|
|
next_function = partial(apply_next_model.func, model)
|
|
|
|
self.lazy_model_operation(next_function, *more_models)
|
|
|
|
apply_next_model.func = function
|
|
|
|
|
|
|
|
# If the model has already been imported and registered, partially
|
|
|
|
# apply it to the function now. If not, add it to the list of
|
|
|
|
# pending operations for the model, where it will be executed with
|
|
|
|
# the model class as its sole argument once the model is ready.
|
|
|
|
try:
|
|
|
|
model_class = self.get_registered_model(*next_model)
|
|
|
|
except LookupError:
|
|
|
|
self._pending_operations[next_model].append(apply_next_model)
|
|
|
|
else:
|
|
|
|
apply_next_model(model_class)
|
2015-03-03 16:43:56 +08:00
|
|
|
|
|
|
|
def do_pending_operations(self, model):
|
|
|
|
"""
|
|
|
|
Take a newly-prepared model and pass it to each function waiting for
|
2017-01-25 04:37:33 +08:00
|
|
|
it. This is called at the very end of Apps.register_model().
|
2015-03-03 16:43:56 +08:00
|
|
|
"""
|
|
|
|
key = model._meta.app_label, model._meta.model_name
|
|
|
|
for function in self._pending_operations.pop(key, []):
|
|
|
|
function(model)
|
2013-12-12 04:44:27 +08:00
|
|
|
|
2016-11-13 01:11:23 +08:00
|
|
|
|
2013-12-30 23:03:06 +08:00
|
|
|
apps = Apps(installed_apps=None)
|