django1/django/db/models/loading.py

270 lines
10 KiB
Python
Raw Normal View History

"Utilities for loading models and the modules that contain them."
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.datastructures import SortedDict
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
from django.utils._os import upath
from django.utils import six
import imp
import sys
import os
__all__ = ('get_apps', 'get_app', 'get_models', 'get_model', 'register_models',
'load_app', 'app_cache_ready')
Fixed #3011 -- Added swappable auth.User models. Thanks to the many people that contributed to the development and review of this patch, including (but not limited to) Jacob Kaplan-Moss, Anssi Kääriäinen, Ramiro Morales, Preston Holmes, Josh Ourisman, Thomas Sutton, and Roger Barnes, as well as the many, many people who have contributed to the design discussion around this ticket over many years. Squashed commit of the following: commit d84749a0f034a0a6906d20df047086b1219040d0 Merge: 531e771 7c11b1a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Wed Sep 26 18:37:04 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit 531e7715da545f930c49919a19e954d41c59b446 Merge: 29d1abb 1f84b04 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Wed Sep 26 07:09:23 2012 +0800 Merged recent trunk changes. commit 29d1abbe351fd5da855fe5ce09e24227d90ddc91 Merge: 8a527dd 54c81a1 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Sep 24 07:49:46 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit 8a527dda13c9bec955b1f7e8db5822d1d9b32a01 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Sep 24 07:48:05 2012 +0800 Ensure sequences are reset correctly in the presence of swapped models. commit e2b6e22f298eb986d74d28b8d9906f37f5ff8eb8 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 23 17:53:05 2012 +0800 Modifications to the handling and docs for auth forms. commit 98aba856b534620aea9091f824b442b47d2fdb3c Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 23 15:28:57 2012 +0800 Improved error handling and docs for get_user_model() commit 0229209c844f06dfeb33b0b8eeec000c127695b6 Merge: 6494bf9 8599f64 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 23 14:50:11 2012 +0800 Merged recent Django trunk changes. commit 6494bf91f2ddaaabec3ec017f2e3131937c35517 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Sep 17 21:38:44 2012 +0800 Improved validation of swappable model settings. commit 5a04cde342cc860384eb844cfda5af55204564ad Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Sep 17 07:15:14 2012 +0800 Removed some unused imports. commit ffd535e4136dc54f084b6ac467e81444696e1c8a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 20:31:28 2012 +0800 Corrected attribute access on for get_by_natural_key commit 913e1ac84c3d9c7c58a9b3bdbbb15ebccd8a8c0a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 20:12:34 2012 +0800 Added test for proxy model safeguards on swappable models. commit 280bf19e94d0d534d0e51bae485c1842558f4ff4 Merge: dbb3900 935a863 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 18:16:49 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit dbb3900775a99df8b6cb1d7063cf364eab55621a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 18:09:27 2012 +0800 Fixes for Python 3 compatibility. commit dfd72131d8664615e245aa0f95b82604ba6b3821 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 15:54:30 2012 +0800 Added protection against proxying swapped models. commit abcb027190e53613e7f1734e77ee185b2587de31 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 15:11:10 2012 +0800 Cleanup and documentation of AbstractUser base class. commit a9491a87763e307f0eb0dc246f54ac865a6ffb34 Merge: fd8bb4e 08bcb4a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 14:46:49 2012 +0800 Merge commit '08bcb4aec1ed154cefc631b8510ee13e9af0c19d' into t3011 commit fd8bb4e3e498a92d7a8b340f0684d5f088aa4c92 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 14:20:14 2012 +0800 Documentation improvements coming from community review. commit b550a6d06d016ab6a0198c4cb2dffe9cceabe8a5 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 13:52:47 2012 +0800 Refactored skipIfCustomUser into the contrib.auth tests. commit 52a02f11107c3f0d711742b8ca65b75175b79d6a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 13:46:10 2012 +0800 Refactored common 'get' pattern into manager method. commit b441a6bbc7d6065175715cb09316b9f13268171b Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 13:41:33 2012 +0800 Added note about backwards incompatible change to admin login messages. commit 08bcb4aec1ed154cefc631b8510ee13e9af0c19d Author: Anssi Kääriäinen <akaariai@gmail.com> Date: Sat Sep 15 18:30:33 2012 +0300 Splitted User to AbstractUser and User commit d9f5e5addbad5e1a01f67e7358e4f5091c3cad81 Author: Anssi Kääriäinen <akaariai@gmail.com> Date: Sat Sep 15 18:30:02 2012 +0300 Reworked REQUIRED_FIELDS + create_user() interaction commit 579f152e4a6e06671e1ac1e59e2b43cf4d764bf4 Merge: 9184972 93e6733 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 15 20:18:37 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit 918497218c58227f5032873ff97261627b2ceab2 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 15 20:18:19 2012 +0800 Deprecate AUTH_PROFILE_MODULE and get_profile(). commit 334cdfc1bb6a6794791497cdefda843bca2ea57a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 15 20:00:12 2012 +0800 Added release notes for new swappable User feature. commit 5d7bb22e8d913b51aba1c3360e7af8b01b6c0ab6 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 15 19:59:49 2012 +0800 Ensure swapped models can't be queried. commit 57ac6e3d32605a67581e875b37ec5b2284711a32 Merge: f2ec915 abfba3b Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 15 14:31:54 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit f2ec915b20f81c8afeaa3df25f80689712f720f8 Merge: 1952656 5e99a3d Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 9 08:29:51 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit 19526563b54fa300785c49cfb625c0c6158ced67 Merge: 2c5e833 c4aa26a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 9 08:22:26 2012 +0800 Merge recent changes from master. commit 2c5e833a30bef4305d55eacc0703533152f5c427 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 9 07:53:46 2012 +0800 Corrected admin_views tests following removal of the email fallback on admin logins. commit 20d1892491839d6ef21f37db4ca136935c2076bf Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 9 01:00:37 2012 +0800 Added conditional skips for all tests dependent on the default User model commit 40ea8b888284775481fc1eaadeff267dbd7e3dfa Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 8 23:47:02 2012 +0800 Added documentation for REQUIRED_FIELDS in custom auth. commit e6aaf659708cf6491f5485d3edfa616cb9214cc0 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 8 23:20:02 2012 +0800 Added first draft of custom User docs. Thanks to Greg Turner for the initial text. commit 75118bd242eec87649da2859e8c50a199a8a1dca Author: Thomas Sutton <me@thomas-sutton.id.au> Date: Mon Aug 20 11:17:26 2012 +0800 Admin app should not allow username discovery The admin app login form should not allow users to discover the username associated with an email address. commit d088b3af58dad7449fc58493193a327725c57c22 Author: Thomas Sutton <me@thomas-sutton.id.au> Date: Mon Aug 20 10:32:13 2012 +0800 Admin app login form should use swapped user model commit 7e82e83d67ee0871a72e1a3a723afdd214fcefc3 Merge: e29c010 39aa890 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Fri Sep 7 23:45:03 2012 +0800 Merged master changes. commit e29c010beb96ca07697c4e3e0c0d5d3ffdc4c0a3 Merge: 8e3fd70 30bdf22 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Aug 20 13:12:57 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit 8e3fd703d02c31a4c3ac9f51f5011d03c0bd47f6 Merge: 507bb50 26e0ba0 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Aug 20 13:09:09 2012 +0800 Merged recent changes from trunk. commit 507bb50a9291bfcdcfa1198f9fea21d4e3b1e762 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Jun 4 20:41:37 2012 +0800 Modified auth app so that login with alternate auth app is possible. commit dabe3628362ab7a4a6c9686dd874803baa997eaa Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Jun 4 20:10:51 2012 +0800 Modified auth management commands to handle custom user definitions. commit 7cc0baf89d490c92ef3f1dc909b8090191a1294b Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Jun 4 14:17:28 2012 +0800 Added model Meta option for swappable models, and made auth.User a swappable model
2012-09-26 18:48:09 +08:00
class AppCache(object):
"""
A cache that stores installed applications and their models. Used to
provide reverse-relations and for app introspection (e.g. admin).
"""
# Use the Borg pattern to share state between all instances. Details at
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531.
__shared_state = dict(
# Keys of app_store are the model modules for each application.
app_store=SortedDict(),
# Mapping of installed app_labels to model modules for that app.
app_labels={},
# Mapping of app_labels to a dictionary of model names to model code.
# May contain apps that are not installed.
app_models=SortedDict(),
# Mapping of app_labels to errors raised when trying to import the app.
app_errors={},
# -- Everything below here is only used when populating the cache --
loaded=False,
handled={},
postponed=[],
nesting_level=0,
_get_models_cache={},
)
def __init__(self):
self.__dict__ = self.__shared_state
def _populate(self):
"""
Fill in all the cache information. This method is threadsafe, in the
sense that every caller will see the same state upon return, and if the
cache is already initialised, it does no work.
"""
if self.loaded:
return
# Note that we want to use the import lock here - the app loading is
# in many cases initiated implicitly by importing, and thus it is
# possible to end up in deadlock when one thread initiates loading
# without holding the importer lock and another thread then tries to
# import something which also launches the app loading. For details of
# this situation see #18251.
imp.acquire_lock()
try:
if self.loaded:
return
for app_name in settings.INSTALLED_APPS:
if app_name in self.handled:
continue
self.load_app(app_name, True)
if not self.nesting_level:
for app_name in self.postponed:
self.load_app(app_name)
self.loaded = True
finally:
imp.release_lock()
def _label_for(self, app_mod):
"""
Return app_label for given models module.
"""
return app_mod.__name__.split('.')[-2]
def load_app(self, app_name, can_postpone=False):
"""
Loads the app with the provided fully qualified name, and returns the
model module.
"""
self.handled[app_name] = None
self.nesting_level += 1
app_module = import_module(app_name)
try:
models = import_module('.models', app_name)
except ImportError:
self.nesting_level -= 1
# If the app doesn't have a models module, we can just ignore the
# ImportError and return no models for it.
if not module_has_submodule(app_module, 'models'):
return None
# But if the app does have a models module, we need to figure out
# whether to suppress or propagate the error. If can_postpone is
# True then it may be that the package is still being imported by
# Python and the models module isn't available yet. So we add the
# app to the postponed list and we'll try it again after all the
# recursion has finished (in populate). If can_postpone is False
# then it's time to raise the ImportError.
else:
if can_postpone:
self.postponed.append(app_name)
return None
else:
raise
self.nesting_level -= 1
if models not in self.app_store:
self.app_store[models] = len(self.app_store)
self.app_labels[self._label_for(models)] = models
return models
def app_cache_ready(self):
"""
Returns true if the model cache is fully populated.
Useful for code that wants to cache the results of get_models() for
themselves once it is safe to do so.
"""
return self.loaded
def get_apps(self):
"Returns a list of all installed modules that contain models."
self._populate()
# Ensure the returned list is always in the same order (with new apps
# added at the end). This avoids unstable ordering on the admin app
# list page, for example.
apps = [(v, k) for k, v in self.app_store.items()]
apps.sort()
return [elt[1] for elt in apps]
def get_app(self, app_label, emptyOK=False):
"""
Returns the module containing the models for the given app_label. If
the app has no models in it and 'emptyOK' is True, returns None.
"""
self._populate()
imp.acquire_lock()
try:
for app_name in settings.INSTALLED_APPS:
if app_label == app_name.split('.')[-1]:
mod = self.load_app(app_name, False)
if mod is None:
if emptyOK:
return None
raise ImproperlyConfigured("App with label %s is missing a models.py module." % app_label)
else:
return mod
raise ImproperlyConfigured("App with label %s could not be found" % app_label)
finally:
imp.release_lock()
def get_app_errors(self):
"Returns the map of known problems with the INSTALLED_APPS."
self._populate()
return self.app_errors
def get_models(self, app_mod=None,
include_auto_created=False, include_deferred=False,
only_installed=True, include_swapped=False):
"""
Given a module containing models, returns a list of the models.
Otherwise returns a list of all installed models.
By default, auto-created models (i.e., m2m models without an
explicit intermediate table) are not included. However, if you
specify include_auto_created=True, they will be.
By default, models created to satisfy deferred attribute
queries are *not* included in the list of models. However, if
you specify include_deferred, they will be.
By default, models that aren't part of installed apps will *not*
be included in the list of models. However, if you specify
only_installed=False, they will be.
By default, models that have been swapped out will *not* be
included in the list of models. However, if you specify
include_swapped, they will be.
"""
cache_key = (app_mod, include_auto_created, include_deferred, only_installed, include_swapped)
try:
return self._get_models_cache[cache_key]
except KeyError:
pass
self._populate()
if app_mod:
if app_mod in self.app_store:
app_list = [self.app_models.get(self._label_for(app_mod),
SortedDict())]
else:
app_list = []
else:
if only_installed:
app_list = [self.app_models.get(app_label, SortedDict())
for app_label in six.iterkeys(self.app_labels)]
else:
app_list = six.itervalues(self.app_models)
model_list = []
for app in app_list:
model_list.extend(
model for model in app.values()
if ((not model._deferred or include_deferred) and
(not model._meta.auto_created or include_auto_created) and
(not model._meta.swapped or include_swapped))
)
self._get_models_cache[cache_key] = model_list
return model_list
def get_model(self, app_label, model_name,
seed_cache=True, only_installed=True):
"""
Returns the model matching the given app_label and case-insensitive
model_name.
Returns None if no model is found.
"""
if seed_cache:
self._populate()
if only_installed and app_label not in self.app_labels:
return None
return self.app_models.get(app_label, SortedDict()).get(model_name.lower())
def register_models(self, app_label, *models):
"""
Register a set of models as belonging to an app.
"""
for model in models:
# Store as 'name: model' pair in a dictionary
# in the app_models dictionary
model_name = model._meta.model_name
model_dict = self.app_models.setdefault(app_label, SortedDict())
if model_name in model_dict:
# The same model may be imported via different paths (e.g.
# appname.models and project.appname.models). We use the source
# filename as a means to detect identity.
fname1 = os.path.abspath(upath(sys.modules[model.__module__].__file__))
fname2 = os.path.abspath(upath(sys.modules[model_dict[model_name].__module__].__file__))
# Since the filename extension could be .py the first time and
# .pyc or .pyo the second time, ignore the extension when
# comparing.
if os.path.splitext(fname1)[0] == os.path.splitext(fname2)[0]:
continue
model_dict[model_name] = model
self._get_models_cache.clear()
cache = AppCache()
# These methods were always module level, so are kept that way for backwards
# compatibility.
get_apps = cache.get_apps
get_app = cache.get_app
get_app_errors = cache.get_app_errors
get_models = cache.get_models
get_model = cache.get_model
register_models = cache.register_models
load_app = cache.load_app
app_cache_ready = cache.app_cache_ready