From 8662654d6d50e4d89f771a757ae5fc83c6b74db0 Mon Sep 17 00:00:00 2001 From: Aymeric Augustin Date: Wed, 11 Dec 2013 23:31:34 +0100 Subject: [PATCH] Removed module-level functions for the app cache. Since the original ones in django.db.models.loading were kept only for backwards compatibility, there's no need to recreate them. However, many internals of Django still relied on them. They were also imported in django.db.models. They never appear in the documentation, except a quick mention of get_models and get_app in the 1.2 release notes to document an edge case in GIS. I don't think that makes them a public API. This commit doesn't change the overall amount of global state but clarifies that it's tied to the app_cache object instead of hiding it behind half a dozen functions. --- django/apps/__init__.py | 1 + django/apps/cache.py | 19 +---------- django/contrib/admin/validation.py | 3 +- django/contrib/admindocs/views.py | 7 ++-- django/contrib/auth/__init__.py | 4 +-- django/contrib/auth/management/__init__.py | 9 ++--- django/contrib/auth/tests/test_management.py | 8 ++--- django/contrib/comments/views/comments.py | 3 +- django/contrib/contenttypes/management.py | 9 ++--- django/contrib/contenttypes/models.py | 3 +- django/contrib/gis/sitemaps/kml.py | 3 +- django/contrib/gis/sitemaps/views.py | 4 +-- .../core/checks/compatibility/django_1_6_0.py | 3 +- django/core/management/base.py | 4 +-- django/core/management/commands/dumpdata.py | 20 +++++------ django/core/management/commands/flush.py | 5 +-- django/core/management/commands/loaddata.py | 4 +-- .../management/commands/makemigrations.py | 6 ++-- django/core/management/commands/migrate.py | 8 ++--- django/core/management/commands/shell.py | 4 +-- .../management/commands/sqlsequencereset.py | 5 +-- django/core/management/sql.py | 9 ++--- django/core/management/validation.py | 14 ++++---- django/core/serializers/base.py | 3 +- django/core/serializers/python.py | 5 +-- django/core/serializers/xml_serializer.py | 3 +- django/db/backends/__init__.py | 13 +++++--- django/db/migrations/loader.py | 9 ++--- django/db/migrations/questioner.py | 4 +-- django/db/migrations/writer.py | 14 ++++---- django/db/models/__init__.py | 3 -- django/db/models/base.py | 5 +-- django/db/models/fields/__init__.py | 4 +-- django/db/models/loading.py | 24 +++++++------- django/db/models/options.py | 8 ++--- django/db/models/signals.py | 4 +-- django/db/utils.py | 4 +-- django/test/simple.py | 8 ++--- django/test/testcases.py | 8 ++--- tests/app_cache/tests.py | 11 ++++--- tests/app_loading/tests.py | 33 ++++++++++--------- tests/commands_sql/tests.py | 15 +++++---- tests/defer_regress/tests.py | 14 ++++---- tests/empty/tests.py | 4 +-- tests/invalid_models/tests.py | 10 +++--- tests/managers_regress/tests.py | 14 ++++---- tests/migrations/test_commands.py | 12 +++---- tests/migrations/test_operations.py | 5 +-- tests/migrations/test_writer.py | 4 +-- tests/proxy_model_inheritance/tests.py | 16 ++++----- tests/proxy_models/tests.py | 6 ++-- tests/runtests.py | 10 +++--- tests/swappable_models/tests.py | 6 ++-- tests/tablespaces/tests.py | 8 ++--- tests/test_suite_override/tests.py | 4 +-- 55 files changed, 226 insertions(+), 220 deletions(-) diff --git a/django/apps/__init__.py b/django/apps/__init__.py index e69de29bb2..0384b1257d 100644 --- a/django/apps/__init__.py +++ b/django/apps/__init__.py @@ -0,0 +1 @@ +from .cache import app_cache, UnavailableApp # NOQA diff --git a/django/apps/cache.py b/django/apps/cache.py index 8afe3dd4cf..b5fd1c37da 100644 --- a/django/apps/cache.py +++ b/django/apps/cache.py @@ -12,8 +12,6 @@ from django.utils.module_loading import module_has_submodule from django.utils._os import upath from django.utils import six -__all__ = ('get_apps', 'get_app', 'get_models', 'get_model', 'register_models', - 'load_app', 'app_cache_ready') MODELS_MODULE_NAME = 'models' @@ -361,19 +359,4 @@ class AppCache(BaseAppCache): self.__dict__ = self.__shared_state -cache = AppCache() - - -# These methods were always module level, so are kept that way for backwards -# compatibility. -get_apps = cache.get_apps -get_app_package = cache.get_app_package -get_app_path = cache.get_app_path -get_app_paths = cache.get_app_paths -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 +app_cache = AppCache() diff --git a/django/contrib/admin/validation.py b/django/contrib/admin/validation.py index 9079678639..c8bd4af120 100644 --- a/django/contrib/admin/validation.py +++ b/django/contrib/admin/validation.py @@ -1,3 +1,4 @@ +from django.apps import app_cache from django.core.exceptions import ImproperlyConfigured from django.db import models from django.db.models.fields import FieldDoesNotExist @@ -17,7 +18,7 @@ class BaseValidator(object): def __init__(self): # Before we can introspect models, they need to be fully loaded so that # inter-relations are set up correctly. We force that here. - models.get_apps() + app_cache.get_apps() def validate(self, cls, model): for m in dir(self): diff --git a/django/contrib/admindocs/views.py b/django/contrib/admindocs/views.py index 482d33e76f..e1edf0aad8 100644 --- a/django/contrib/admindocs/views.py +++ b/django/contrib/admindocs/views.py @@ -4,6 +4,7 @@ import os import re from django import template +from django.apps import app_cache from django.conf import settings from django.contrib import admin from django.contrib.admin.views.decorators import staff_member_required @@ -182,7 +183,7 @@ class ModelIndexView(BaseAdminDocsView): template_name = 'admin_doc/model_index.html' def get_context_data(self, **kwargs): - m_list = [m._meta for m in models.get_models()] + m_list = [m._meta for m in app_cache.get_models()] kwargs.update({'models': m_list}) return super(ModelIndexView, self).get_context_data(**kwargs) @@ -193,11 +194,11 @@ class ModelDetailView(BaseAdminDocsView): def get_context_data(self, **kwargs): # Get the model class. try: - app_mod = models.get_app(self.kwargs['app_label']) + app_mod = app_cache.get_app(self.kwargs['app_label']) except ImproperlyConfigured: raise Http404(_("App %r not found") % self.kwargs['app_label']) model = None - for m in models.get_models(app_mod): + for m in app_cache.get_models(app_mod): if m._meta.model_name == self.kwargs['model_name']: model = m break diff --git a/django/contrib/auth/__init__.py b/django/contrib/auth/__init__.py index 83aa445bac..3c5a40c184 100644 --- a/django/contrib/auth/__init__.py +++ b/django/contrib/auth/__init__.py @@ -123,13 +123,13 @@ def get_user_model(): """ Returns the User model that is active in this project. """ - from django.db.models import get_model + from django.apps import app_cache try: app_label, model_name = settings.AUTH_USER_MODEL.split('.') except ValueError: raise ImproperlyConfigured("AUTH_USER_MODEL must be of the form 'app_label.model_name'") - user_model = get_model(app_label, model_name) + user_model = app_cache.get_model(app_label, model_name) if user_model is None: raise ImproperlyConfigured("AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL) return user_model diff --git a/django/contrib/auth/management/__init__.py b/django/contrib/auth/management/__init__.py index 8fd08ac57c..5f24bf069e 100644 --- a/django/contrib/auth/management/__init__.py +++ b/django/contrib/auth/management/__init__.py @@ -6,12 +6,13 @@ from __future__ import unicode_literals import getpass import unicodedata +from django.apps import app_cache, UnavailableApp from django.contrib.auth import (models as auth_app, get_permission_codename, get_user_model) from django.core import exceptions from django.core.management.base import CommandError from django.db import DEFAULT_DB_ALIAS, router -from django.db.models import get_model, get_models, signals, UnavailableApp +from django.db.models import signals from django.utils.encoding import DEFAULT_LOCALE_ENCODING from django.utils import six from django.utils.six.moves import input @@ -61,7 +62,7 @@ def _check_permission_clashing(custom, builtin, ctype): def create_permissions(app, created_models, verbosity, db=DEFAULT_DB_ALIAS, **kwargs): try: - get_model('auth', 'Permission') + app_cache.get_model('auth', 'Permission') except UnavailableApp: return @@ -70,7 +71,7 @@ def create_permissions(app, created_models, verbosity, db=DEFAULT_DB_ALIAS, **kw from django.contrib.contenttypes.models import ContentType - app_models = get_models(app) + app_models = app_cache.get_models(app) # This will hold the permissions we're looking for as # (content_type, (codename, name)) @@ -119,7 +120,7 @@ def create_permissions(app, created_models, verbosity, db=DEFAULT_DB_ALIAS, **kw def create_superuser(app, created_models, verbosity, db, **kwargs): try: - get_model('auth', 'Permission') + app_cache.get_model('auth', 'Permission') UserModel = get_user_model() except UnavailableApp: return diff --git a/django/contrib/auth/tests/test_management.py b/django/contrib/auth/tests/test_management.py index 698947d57c..43ad15dcab 100644 --- a/django/contrib/auth/tests/test_management.py +++ b/django/contrib/auth/tests/test_management.py @@ -1,7 +1,7 @@ from __future__ import unicode_literals from datetime import date -from django.apps.cache import get_app +from django.apps import app_cache from django.contrib.auth import models, management from django.contrib.auth.management import create_permissions from django.contrib.auth.management.commands import changepassword @@ -184,21 +184,21 @@ class CustomUserModelValidationTestCase(TestCase): def test_required_fields_is_list(self): "REQUIRED_FIELDS should be a list." new_io = StringIO() - get_validation_errors(new_io, get_app('auth')) + get_validation_errors(new_io, app_cache.get_app('auth')) self.assertIn("The REQUIRED_FIELDS must be a list or tuple.", new_io.getvalue()) @override_settings(AUTH_USER_MODEL='auth.CustomUserBadRequiredFields') def test_username_not_in_required_fields(self): "USERNAME_FIELD should not appear in REQUIRED_FIELDS." new_io = StringIO() - get_validation_errors(new_io, get_app('auth')) + get_validation_errors(new_io, app_cache.get_app('auth')) self.assertIn("The field named as the USERNAME_FIELD should not be included in REQUIRED_FIELDS on a swappable User model.", new_io.getvalue()) @override_settings(AUTH_USER_MODEL='auth.CustomUserNonUniqueUsername') def test_username_non_unique(self): "A non-unique USERNAME_FIELD should raise a model validation error." new_io = StringIO() - get_validation_errors(new_io, get_app('auth')) + get_validation_errors(new_io, app_cache.get_app('auth')) self.assertIn("The USERNAME_FIELD must be unique. Add unique=True to the field parameters.", new_io.getvalue()) diff --git a/django/contrib/comments/views/comments.py b/django/contrib/comments/views/comments.py index a2cbe33c0e..5d7c543adb 100644 --- a/django/contrib/comments/views/comments.py +++ b/django/contrib/comments/views/comments.py @@ -1,4 +1,5 @@ from django import http +from django.apps import app_cache from django.conf import settings from django.contrib import comments from django.contrib.comments import signals @@ -48,7 +49,7 @@ def post_comment(request, next=None, using=None): if ctype is None or object_pk is None: return CommentPostBadRequest("Missing content_type or object_pk field.") try: - model = models.get_model(*ctype.split(".", 1)) + model = app_cache.get_model(*ctype.split(".", 1)) target = model._default_manager.using(using).get(pk=object_pk) except TypeError: return CommentPostBadRequest( diff --git a/django/contrib/contenttypes/management.py b/django/contrib/contenttypes/management.py index 3d2fc4b95e..477464c37e 100644 --- a/django/contrib/contenttypes/management.py +++ b/django/contrib/contenttypes/management.py @@ -1,6 +1,7 @@ +from django.apps import app_cache, UnavailableApp from django.contrib.contenttypes.models import ContentType from django.db import DEFAULT_DB_ALIAS, router -from django.db.models import get_apps, get_model, get_models, signals, UnavailableApp +from django.db.models import signals from django.utils.encoding import smart_text from django.utils import six from django.utils.six.moves import input @@ -12,7 +13,7 @@ def update_contenttypes(app, created_models, verbosity=2, db=DEFAULT_DB_ALIAS, * entries that no longer have a matching model class. """ try: - get_model('contenttypes', 'ContentType') + app_cache.get_model('contenttypes', 'ContentType') except UnavailableApp: return @@ -20,7 +21,7 @@ def update_contenttypes(app, created_models, verbosity=2, db=DEFAULT_DB_ALIAS, * return ContentType.objects.clear_cache() - app_models = get_models(app) + app_models = app_cache.get_models(app) if not app_models: return # They all have the same app_label, get the first one. @@ -85,7 +86,7 @@ If you're unsure, answer 'no'. def update_all_contenttypes(verbosity=2, **kwargs): - for app in get_apps(): + for app in app_cache.get_apps(): update_contenttypes(app, None, verbosity, **kwargs) signals.post_migrate.connect(update_contenttypes) diff --git a/django/contrib/contenttypes/models.py b/django/contrib/contenttypes/models.py index aec15d6664..90dea5b811 100644 --- a/django/contrib/contenttypes/models.py +++ b/django/contrib/contenttypes/models.py @@ -1,3 +1,4 @@ +from django.apps import app_cache from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import smart_text, force_text @@ -156,7 +157,7 @@ class ContentType(models.Model): def model_class(self): "Returns the Python model class for this type of content." - return models.get_model(self.app_label, self.model, + return app_cache.get_model(self.app_label, self.model, only_installed=False) def get_object_for_this_type(self, **kwargs): diff --git a/django/contrib/gis/sitemaps/kml.py b/django/contrib/gis/sitemaps/kml.py index 5e74c6c47d..1e4fc82550 100644 --- a/django/contrib/gis/sitemaps/kml.py +++ b/django/contrib/gis/sitemaps/kml.py @@ -1,3 +1,4 @@ +from django.apps import app_cache from django.core import urlresolvers from django.contrib.sitemaps import Sitemap from django.contrib.gis.db.models.fields import GeometryField @@ -25,7 +26,7 @@ class KMLSitemap(Sitemap): """ kml_sources = [] if sources is None: - sources = models.get_models() + sources = app_cache.get_models() for source in sources: if isinstance(source, models.base.ModelBase): for field in source._meta.fields: diff --git a/django/contrib/gis/sitemaps/views.py b/django/contrib/gis/sitemaps/views.py index 0672b800cc..e68523981e 100644 --- a/django/contrib/gis/sitemaps/views.py +++ b/django/contrib/gis/sitemaps/views.py @@ -2,6 +2,7 @@ from __future__ import unicode_literals import warnings +from django.apps import app_cache from django.http import HttpResponse, Http404 from django.template import loader from django.contrib.sites.models import get_current_site @@ -9,7 +10,6 @@ from django.core import urlresolvers from django.core.paginator import EmptyPage, PageNotAnInteger from django.contrib.gis.db.models.fields import GeometryField from django.db import connections, DEFAULT_DB_ALIAS -from django.db.models import get_model from django.db.models.fields import FieldDoesNotExist from django.utils import six from django.utils.translation import ugettext as _ @@ -81,7 +81,7 @@ def kml(request, label, model, field_name=None, compress=False, using=DEFAULT_DB must be that of a geographic field. """ placemarks = [] - klass = get_model(label, model) + klass = app_cache.get_model(label, model) if not klass: raise Http404('You must supply a valid app label and module name. Got "%s.%s"' % (label, model)) diff --git a/django/core/checks/compatibility/django_1_6_0.py b/django/core/checks/compatibility/django_1_6_0.py index a00196f2c0..a42249de60 100644 --- a/django/core/checks/compatibility/django_1_6_0.py +++ b/django/core/checks/compatibility/django_1_6_0.py @@ -1,5 +1,6 @@ from __future__ import unicode_literals +from django.apps import app_cache from django.db import models @@ -31,7 +32,7 @@ def check_boolean_field_default_value(): warns the user that the default has changed from False to Null. """ fields = [] - for cls in models.get_models(): + for cls in app_cache.get_models(): opts = cls._meta for f in opts.local_fields: if isinstance(f, models.BooleanField) and not f.has_default(): diff --git a/django/core/management/base.py b/django/core/management/base.py index ef967d021f..d749bc2e8e 100644 --- a/django/core/management/base.py +++ b/django/core/management/base.py @@ -342,11 +342,11 @@ class AppCommand(BaseCommand): args = '' def handle(self, *app_labels, **options): - from django.db import models + from django.apps import app_cache if not app_labels: raise CommandError('Enter at least one appname.') try: - app_list = [models.get_app(app_label) for app_label in app_labels] + app_list = [app_cache.get_app(app_label) for app_label in app_labels] except (ImproperlyConfigured, ImportError) as e: raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e) output = [] diff --git a/django/core/management/commands/dumpdata.py b/django/core/management/commands/dumpdata.py index 85817e9194..4f87b04003 100644 --- a/django/core/management/commands/dumpdata.py +++ b/django/core/management/commands/dumpdata.py @@ -38,7 +38,7 @@ class Command(BaseCommand): args = '[appname appname.ModelName ...]' def handle(self, *app_labels, **options): - from django.db.models import get_app, get_apps, get_model + from django.apps import app_cache format = options.get('format') indent = options.get('indent') @@ -64,13 +64,13 @@ class Command(BaseCommand): for exclude in excludes: if '.' in exclude: app_label, model_name = exclude.split('.', 1) - model_obj = get_model(app_label, model_name) + model_obj = app_cache.get_model(app_label, model_name) if not model_obj: raise CommandError('Unknown model in excludes: %s' % exclude) excluded_models.add(model_obj) else: try: - app_obj = get_app(exclude) + app_obj = app_cache.get_app(exclude) excluded_apps.add(app_obj) except ImproperlyConfigured: raise CommandError('Unknown app in excludes: %s' % exclude) @@ -78,7 +78,7 @@ class Command(BaseCommand): if len(app_labels) == 0: if primary_keys: raise CommandError("You can only use --pks option with one model") - app_list = OrderedDict((app, None) for app in get_apps() if app not in excluded_apps) + app_list = OrderedDict((app, None) for app in app_cache.get_apps() if app not in excluded_apps) else: if len(app_labels) > 1 and primary_keys: raise CommandError("You can only use --pks option with one model") @@ -87,12 +87,12 @@ class Command(BaseCommand): try: app_label, model_label = label.split('.') try: - app = get_app(app_label) + app = app_cache.get_app(app_label) except ImproperlyConfigured: raise CommandError("Unknown application: %s" % app_label) if app in excluded_apps: continue - model = get_model(app_label, model_label) + model = app_cache.get_model(app_label, model_label) if model is None: raise CommandError("Unknown model: %s.%s" % (app_label, model_label)) @@ -107,7 +107,7 @@ class Command(BaseCommand): # This is just an app - no model qualifier app_label = label try: - app = get_app(app_label) + app = app_cache.get_app(app_label) except ImproperlyConfigured: raise CommandError("Unknown application: %s" % app_label) if app in excluded_apps: @@ -160,13 +160,13 @@ def sort_dependencies(app_list): is serialized before a normal model, and any model with a natural key dependency has it's dependencies serialized first. """ - from django.db.models import get_model, get_models + from django.apps import app_cache # Process the list of models, and get the list of dependencies model_dependencies = [] models = set() for app, model_list in app_list: if model_list is None: - model_list = get_models(app) + model_list = app_cache.get_models(app) for model in model_list: models.add(model) @@ -174,7 +174,7 @@ def sort_dependencies(app_list): if hasattr(model, 'natural_key'): deps = getattr(model.natural_key, 'dependencies', []) if deps: - deps = [get_model(*d.split('.')) for d in deps] + deps = [app_cache.get_model(*d.split('.')) for d in deps] else: deps = [] diff --git a/django/core/management/commands/flush.py b/django/core/management/commands/flush.py index 130338a55a..f4b221a32c 100644 --- a/django/core/management/commands/flush.py +++ b/django/core/management/commands/flush.py @@ -2,8 +2,9 @@ import sys from importlib import import_module from optparse import make_option +from django.apps import app_cache from django.conf import settings -from django.db import connections, router, transaction, models, DEFAULT_DB_ALIAS +from django.db import connections, router, transaction, DEFAULT_DB_ALIAS from django.core.management import call_command from django.core.management.base import NoArgsCommand, CommandError from django.core.management.color import no_style @@ -93,6 +94,6 @@ Are you sure you want to do this? # Emit the post migrate signal. This allows individual applications to # respond as if the database had been migrated from scratch. all_models = [] - for app in models.get_apps(): + for app in app_cache.get_apps(): all_models.extend(router.get_migratable_models(app, database, include_auto_created=True)) emit_post_migrate_signal(set(all_models), verbosity, interactive, database) diff --git a/django/core/management/commands/loaddata.py b/django/core/management/commands/loaddata.py index 59c1343271..64a57fbc79 100644 --- a/django/core/management/commands/loaddata.py +++ b/django/core/management/commands/loaddata.py @@ -7,13 +7,13 @@ import warnings import zipfile from optparse import make_option +from django.apps import app_cache from django.conf import settings from django.core import serializers from django.core.management.base import BaseCommand, CommandError from django.core.management.color import no_style from django.db import (connections, router, transaction, DEFAULT_DB_ALIAS, IntegrityError, DatabaseError) -from django.db.models import get_app_paths from django.utils import lru_cache from django.utils.encoding import force_text from django.utils.functional import cached_property @@ -230,7 +230,7 @@ class Command(BaseCommand): current directory. """ dirs = [] - for path in get_app_paths(): + for path in app_cache.get_app_paths(): d = os.path.join(path, 'fixtures') if os.path.isdir(d): dirs.append(d) diff --git a/django/core/management/commands/makemigrations.py b/django/core/management/commands/makemigrations.py index 7c4bb4f7cf..cd891c404d 100644 --- a/django/core/management/commands/makemigrations.py +++ b/django/core/management/commands/makemigrations.py @@ -3,7 +3,7 @@ import os import operator from optparse import make_option -from django.apps.cache import cache +from django.apps import app_cache from django.core.management.base import BaseCommand, CommandError from django.core.exceptions import ImproperlyConfigured from django.db import connections, DEFAULT_DB_ALIAS, migrations @@ -38,7 +38,7 @@ class Command(BaseCommand): bad_app_labels = set() for app_label in app_labels: try: - cache.get_app(app_label) + app_cache.get_app(app_label) except ImproperlyConfigured: bad_app_labels.add(app_label) if bad_app_labels: @@ -73,7 +73,7 @@ class Command(BaseCommand): # Detect changes autodetector = MigrationAutodetector( loader.graph.project_state(), - ProjectState.from_app_cache(cache), + ProjectState.from_app_cache(app_cache), InteractiveMigrationQuestioner(specified_apps=app_labels), ) changes = autodetector.changes(graph=loader.graph, trim_to_apps=app_labels or None) diff --git a/django/core/management/commands/migrate.py b/django/core/management/commands/migrate.py index 1966223042..39a2d9a784 100644 --- a/django/core/management/commands/migrate.py +++ b/django/core/management/commands/migrate.py @@ -6,13 +6,13 @@ from importlib import import_module import itertools import traceback -from django.apps.cache import cache +from django.apps import app_cache from django.conf import settings from django.core.management import call_command from django.core.management.base import BaseCommand, CommandError from django.core.management.color import no_style from django.core.management.sql import custom_sql_for_model, emit_post_migrate_signal, emit_pre_migrate_signal -from django.db import connections, router, transaction, models, DEFAULT_DB_ALIAS +from django.db import connections, router, transaction, DEFAULT_DB_ALIAS from django.db.migrations.executor import MigrationExecutor from django.db.migrations.loader import MigrationLoader, AmbiguityError from django.db.migrations.state import ProjectState @@ -136,7 +136,7 @@ class Command(BaseCommand): # If there's changes that aren't in migrations yet, tell them how to fix it. autodetector = MigrationAutodetector( executor.loader.graph.project_state(), - ProjectState.from_app_cache(cache), + ProjectState.from_app_cache(app_cache), ) changes = autodetector.changes(graph=executor.loader.graph) if changes: @@ -182,7 +182,7 @@ class Command(BaseCommand): all_models = [ (app.__name__.split('.')[-2], router.get_migratable_models(app, connection.alias, include_auto_created=True)) - for app in models.get_apps() if app.__name__.split('.')[-2] in apps + for app in app_cache.get_apps() if app.__name__.split('.')[-2] in apps ] def model_installed(model): diff --git a/django/core/management/commands/shell.py b/django/core/management/commands/shell.py index 0d84c9b2ec..12af814161 100644 --- a/django/core/management/commands/shell.py +++ b/django/core/management/commands/shell.py @@ -66,8 +66,8 @@ class Command(NoArgsCommand): def handle_noargs(self, **options): # XXX: (Temporary) workaround for ticket #1796: force early loading of all # models from installed apps. - from django.apps.cache import get_models - get_models() + from django.apps import app_cache + app_cache.get_models() use_plain = options.get('plain', False) no_startup = options.get('no_startup', False) diff --git a/django/core/management/commands/sqlsequencereset.py b/django/core/management/commands/sqlsequencereset.py index 8f4ea823c7..24ec25e8ed 100644 --- a/django/core/management/commands/sqlsequencereset.py +++ b/django/core/management/commands/sqlsequencereset.py @@ -2,8 +2,9 @@ from __future__ import unicode_literals from optparse import make_option +from django.apps import app_cache from django.core.management.base import AppCommand -from django.db import connections, models, DEFAULT_DB_ALIAS +from django.db import connections, DEFAULT_DB_ALIAS class Command(AppCommand): @@ -20,4 +21,4 @@ class Command(AppCommand): def handle_app(self, app, **options): connection = connections[options.get('database')] - return '\n'.join(connection.ops.sequence_reset_sql(self.style, models.get_models(app, include_auto_created=True))) + return '\n'.join(connection.ops.sequence_reset_sql(self.style, app_cache.get_models(app, include_auto_created=True))) diff --git a/django/core/management/sql.py b/django/core/management/sql.py index 6f60d73ae9..bcd4769dde 100644 --- a/django/core/management/sql.py +++ b/django/core/management/sql.py @@ -5,6 +5,7 @@ import os import re import warnings +from django.apps import app_cache from django.conf import settings from django.core.management.base import CommandError from django.db import models, router @@ -24,7 +25,7 @@ def sql_create(app, style, connection): # We trim models from the current app so that the sqlreset command does not # generate invalid SQL (leaving models out of known_models is harmless, so # we can be conservative). - app_models = models.get_models(app, include_auto_created=True) + app_models = app_cache.get_models(app, include_auto_created=True) final_output = [] tables = connection.introspection.table_names() known_models = set(model for model in connection.introspection.installed_models(tables) if model not in app_models) @@ -168,7 +169,7 @@ def _split_statements(content): def custom_sql_for_model(model, style, connection): opts = model._meta app_dirs = [] - app_dir = models.get_app_path(model._meta.app_label) + app_dir = app_cache.get_app_path(model._meta.app_label) app_dirs.append(os.path.normpath(os.path.join(app_dir, 'sql'))) # Deprecated location -- remove in Django 1.9 @@ -206,7 +207,7 @@ def custom_sql_for_model(model, style, connection): def emit_pre_migrate_signal(create_models, verbosity, interactive, db): # Emit the pre_migrate signal for every application. - for app in models.get_apps(): + for app in app_cache.get_apps(): app_name = app.__name__.split('.')[-2] if verbosity >= 2: print("Running pre-migrate handlers for application %s" % app_name) @@ -219,7 +220,7 @@ def emit_pre_migrate_signal(create_models, verbosity, interactive, db): def emit_post_migrate_signal(created_models, verbosity, interactive, db): # Emit the post_migrate signal for every application. - for app in models.get_apps(): + for app in app_cache.get_apps(): app_name = app.__name__.split('.')[-2] if verbosity >= 2: print("Running post-migrate handlers for application %s" % app_name) diff --git a/django/core/management/validation.py b/django/core/management/validation.py index 459923a088..89aa5ad068 100644 --- a/django/core/management/validation.py +++ b/django/core/management/validation.py @@ -26,16 +26,16 @@ def get_validation_errors(outfile, app=None): validates all models of all installed apps. Writes errors, if any, to outfile. Returns number of errors. """ - from django.apps.cache import get_app_errors + from django.apps import app_cache from django.db import connection, models from django.db.models.deletion import SET_NULL, SET_DEFAULT e = ModelErrorCollection(outfile) - for (app_name, error) in get_app_errors().items(): + for (app_name, error) in app_cache.get_app_errors().items(): e.add(app_name, error) - for cls in models.get_models(app, include_swapped=True): + for cls in app_cache.get_models(app, include_swapped=True): opts = cls._meta # Check swappable attribute. @@ -45,7 +45,7 @@ def get_validation_errors(outfile, app=None): except ValueError: e.add(opts, "%s is not of the form 'app_label.app_name'." % opts.swappable) continue - if not models.get_model(app_label, model_name): + if not app_cache.get_model(app_label, model_name): e.add(opts, "Model has been swapped out for '%s' which has not been installed or is abstract." % opts.swapped) # No need to perform any other validation checks on a swapped model. continue @@ -155,7 +155,7 @@ def get_validation_errors(outfile, app=None): # Check to see if the related field will clash with any existing # fields, m2m fields, m2m related objects or related objects if f.rel: - if f.rel.to not in models.get_models(): + if f.rel.to not in app_cache.get_models(): # If the related model is swapped, provide a hint; # otherwise, the model just hasn't been installed. if not isinstance(f.rel.to, six.string_types) and f.rel.to._meta.swapped: @@ -210,7 +210,7 @@ def get_validation_errors(outfile, app=None): # Check to see if the related m2m field will clash with any # existing fields, m2m fields, m2m related objects or related # objects - if f.rel.to not in models.get_models(): + if f.rel.to not in app_cache.get_models(): # If the related model is swapped, provide a hint; # otherwise, the model just hasn't been installed. if not isinstance(f.rel.to, six.string_types) and f.rel.to._meta.swapped: @@ -268,7 +268,7 @@ def get_validation_errors(outfile, app=None): ) else: seen_to = True - if f.rel.through not in models.get_models(include_auto_created=True): + if f.rel.through not in app_cache.get_models(include_auto_created=True): e.add(opts, "'%s' specifies an m2m relation through model " "%s, which has not been installed." % (f.name, f.rel.through)) signature = (f.rel.to, cls, f.rel.through) diff --git a/django/core/serializers/base.py b/django/core/serializers/base.py index b7d3e28a0d..e575c1d1c2 100644 --- a/django/core/serializers/base.py +++ b/django/core/serializers/base.py @@ -3,6 +3,7 @@ Module for abstract serializer/unserializer base classes. """ import warnings +from django.apps import app_cache from django.db import models from django.utils import six @@ -139,7 +140,7 @@ class Deserializer(six.Iterator): # hack to make sure that the models have all been loaded before # deserialization starts (otherwise subclass calls to get_model() # and friends might fail...) - models.get_apps() + app_cache.get_apps() def __iter__(self): return self diff --git a/django/core/serializers/python.py b/django/core/serializers/python.py index 4ac7cc4cf1..07f857a198 100644 --- a/django/core/serializers/python.py +++ b/django/core/serializers/python.py @@ -5,6 +5,7 @@ other serializers. """ from __future__ import unicode_literals +from django.apps import app_cache from django.conf import settings from django.core.serializers import base from django.db import models, DEFAULT_DB_ALIAS @@ -87,7 +88,7 @@ def Deserializer(object_list, **options): db = options.pop('using', DEFAULT_DB_ALIAS) ignore = options.pop('ignorenonexistent', False) - models.get_apps() + app_cache.get_apps() for d in object_list: # Look up the model and starting build a dict of data for it. Model = _get_model(d["model"]) @@ -153,7 +154,7 @@ def _get_model(model_identifier): Helper to look up a model from an "app_label.model_name" string. """ try: - Model = models.get_model(*model_identifier.split(".")) + Model = app_cache.get_model(*model_identifier.split(".")) except TypeError: Model = None if Model is None: diff --git a/django/core/serializers/xml_serializer.py b/django/core/serializers/xml_serializer.py index 6870ac7d44..e9bea84bb1 100644 --- a/django/core/serializers/xml_serializer.py +++ b/django/core/serializers/xml_serializer.py @@ -4,6 +4,7 @@ XML serializer. from __future__ import unicode_literals +from django.apps import app_cache from django.conf import settings from django.core.serializers import base from django.db import models, DEFAULT_DB_ALIAS @@ -276,7 +277,7 @@ class Deserializer(base.Deserializer): "<%s> node is missing the required '%s' attribute" % (node.nodeName, attr)) try: - Model = models.get_model(*model_identifier.split(".")) + Model = app_cache.get_model(*model_identifier.split(".")) except TypeError: Model = None if Model is None: diff --git a/django/db/backends/__init__.py b/django/db/backends/__init__.py index 3faaeffb21..edbca0e557 100644 --- a/django/db/backends/__init__.py +++ b/django/db/backends/__init__.py @@ -1268,9 +1268,10 @@ class BaseDatabaseIntrospection(object): If only_existing is True, the resulting list will only include the tables that actually exist in the database. """ - from django.db import models, router + from django.apps import app_cache + from django.db import router tables = set() - for app in models.get_apps(): + for app in app_cache.get_apps(): for model in router.get_migratable_models(app, self.connection.alias): if not model._meta.managed: continue @@ -1288,9 +1289,10 @@ class BaseDatabaseIntrospection(object): def installed_models(self, tables): "Returns a set of all models represented by the provided list of table names." - from django.db import models, router + from django.apps import app_cache + from django.db import router all_models = [] - for app in models.get_apps(): + for app in app_cache.get_apps(): all_models.extend(router.get_migratable_models(app, self.connection.alias)) tables = list(map(self.table_name_converter, tables)) return set([ @@ -1300,9 +1302,10 @@ class BaseDatabaseIntrospection(object): def sequence_list(self): "Returns a list of information about all DB sequences for all models in all apps." + from django.apps import app_cache from django.db import models, router - apps = models.get_apps() + apps = app_cache.get_apps() sequence_list = [] for app in apps: diff --git a/django/db/migrations/loader.py b/django/db/migrations/loader.py index 101588c4a1..f4a7168441 100644 --- a/django/db/migrations/loader.py +++ b/django/db/migrations/loader.py @@ -1,7 +1,8 @@ +from importlib import import_module import os import sys -from importlib import import_module -from django.apps.cache import cache + +from django.apps import app_cache from django.db.migrations.recorder import MigrationRecorder from django.db.migrations.graph import MigrationGraph from django.utils import six @@ -45,7 +46,7 @@ class MigrationLoader(object): if app_label in settings.MIGRATION_MODULES: return settings.MIGRATION_MODULES[app_label] else: - return '%s.migrations' % cache.get_app_package(app_label) + return '%s.migrations' % app_cache.get_app_package(app_label) def load_disk(self): """ @@ -54,7 +55,7 @@ class MigrationLoader(object): self.disk_migrations = {} self.unmigrated_apps = set() self.migrated_apps = set() - for app in cache.get_apps(): + for app in app_cache.get_apps(): # Get the migrations module directory app_label = app.__name__.split(".")[-2] module_name = self.migrations_module(app_label) diff --git a/django/db/migrations/questioner.py b/django/db/migrations/questioner.py index 7874f23ed0..d9446f8d88 100644 --- a/django/db/migrations/questioner.py +++ b/django/db/migrations/questioner.py @@ -2,7 +2,7 @@ import importlib import os import sys -from django.apps.cache import cache +from django.apps import app_cache from django.utils import datetime_safe from django.utils.six.moves import input from django.core.exceptions import ImproperlyConfigured @@ -29,7 +29,7 @@ class MigrationQuestioner(object): # Apps from the new app template will have these; the python # file check will ensure we skip South ones. try: - models_module = cache.get_app(app_label) + models_module = app_cache.get_app(app_label) except ImproperlyConfigured: # It's a fake app return self.defaults.get("ask_initial", False) migrations_import_path = "%s.migrations" % models_module.__package__ diff --git a/django/db/migrations/writer.py b/django/db/migrations/writer.py index 150455b09c..9356c8d8aa 100644 --- a/django/db/migrations/writer.py +++ b/django/db/migrations/writer.py @@ -1,9 +1,11 @@ from __future__ import unicode_literals + import datetime -import types -import os from importlib import import_module -from django.apps.cache import cache +import os +import types + +from django.apps import app_cache from django.db import models from django.db.migrations.loader import MigrationLoader from django.utils.encoding import force_text @@ -67,9 +69,9 @@ class MigrationWriter(object): migrations_module = import_module(migrations_package_name) basedir = os.path.dirname(migrations_module.__file__) except ImportError: - app = cache.get_app(self.migration.app_label) - app_path = cache._get_app_path(app) - app_package_name = cache._get_app_package(app) + app = app_cache.get_app(self.migration.app_label) + app_path = app_cache._get_app_path(app) + app_package_name = app_cache._get_app_package(app) migrations_package_basename = migrations_package_name.split(".")[-1] # Alright, see if it's a direct submodule of the app diff --git a/django/db/models/__init__.py b/django/db/models/__init__.py index ad76347494..265550fcce 100644 --- a/django/db/models/__init__.py +++ b/django/db/models/__init__.py @@ -1,8 +1,5 @@ from functools import wraps -from django.apps.cache import ( # NOQA - get_apps, get_app_path, get_app_paths, get_app, get_models, get_model, - register_models, UnavailableApp) from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured # NOQA from django.db.models.query import Q, QuerySet, Prefetch # NOQA from django.db.models.expressions import F # NOQA diff --git a/django/db/models/base.py b/django/db/models/base.py index f22506aa92..94d7234142 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -5,7 +5,8 @@ import sys from functools import update_wrapper from django.utils.six.moves import zip -from django.apps.cache import get_model, MODELS_MODULE_NAME +from django.apps import app_cache +from django.apps.cache import MODELS_MODULE_NAME import django.db.models.manager # NOQA: Imported to register signal handler. from django.conf import settings from django.core.exceptions import (ObjectDoesNotExist, @@ -1066,7 +1067,7 @@ def model_unpickle(model_id, attrs, factory): Used to unpickle Model subclasses with deferred fields. """ if isinstance(model_id, tuple): - model = get_model(*model_id) + model = app_cache.get_model(*model_id) else: # Backwards compat - the model was cached directly in earlier versions. model = model_id diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py index d69a4346e2..830ff2efa2 100644 --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -9,7 +9,7 @@ import warnings from base64 import b64decode, b64encode from itertools import tee -from django.apps.cache import get_model +from django.apps import app_cache from django.db import connection from django.db.models.query_utils import QueryWrapper from django.conf import settings @@ -51,7 +51,7 @@ BLANK_CHOICE_DASH = [("", "---------")] def _load_field(app_label, model_name, field_name): - return get_model(app_label, model_name)._meta.get_field_by_name(field_name)[0] + return app_cache.get_model(app_label, model_name)._meta.get_field_by_name(field_name)[0] class FieldDoesNotExist(Exception): diff --git a/django/db/models/loading.py b/django/db/models/loading.py index 795de130b5..1371a15fdf 100644 --- a/django/db/models/loading.py +++ b/django/db/models/loading.py @@ -1,6 +1,6 @@ import warnings -from django.apps.cache import cache +from django.apps import app_cache warnings.warn( "The utilities in django.db.models.loading are deprecated " @@ -12,14 +12,14 @@ __all__ = ('get_apps', 'get_app', 'get_models', 'get_model', 'register_models', # These methods were always module level, so are kept that way for backwards # compatibility. -get_apps = cache.get_apps -get_app_package = cache.get_app_package -get_app_path = cache.get_app_path -get_app_paths = cache.get_app_paths -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 +get_apps = app_cache.get_apps +get_app_package = app_cache.get_app_package +get_app_path = app_cache.get_app_path +get_app_paths = app_cache.get_app_paths +get_app = app_cache.get_app +get_app_errors = app_cache.get_app_errors +get_models = app_cache.get_models +get_model = app_cache.get_model +register_models = app_cache.register_models +load_app = app_cache.load_app +app_cache_ready = app_cache.app_cache_ready diff --git a/django/db/models/options.py b/django/db/models/options.py index 5d99066343..74090cb921 100644 --- a/django/db/models/options.py +++ b/django/db/models/options.py @@ -5,7 +5,7 @@ import re from bisect import bisect import warnings -from django.apps.cache import app_cache_ready, cache +from django.apps import app_cache from django.conf import settings from django.db.models.fields.related import ManyToManyRel from django.db.models.fields import AutoField, FieldDoesNotExist @@ -89,7 +89,7 @@ class Options(object): self.related_fkey_lookups = [] # A custom AppCache to use, if you're making a separate model set. - self.app_cache = cache + self.app_cache = app_cache def contribute_to_class(self, cls, name): from django.db import connection @@ -432,7 +432,7 @@ class Options(object): if hasattr(f, 'related'): cache[f.name] = cache[f.attname] = ( f.related, None if f.model == self.model else f.model, True, False) - if app_cache_ready(): + if app_cache.app_cache_ready(): self._name_map = cache return cache @@ -558,7 +558,7 @@ class Options(object): and not isinstance(f.rel.to, six.string_types) and self == f.rel.to._meta): cache[f.related] = None - if app_cache_ready(): + if app_cache.app_cache_ready(): self._related_many_to_many_cache = cache return cache diff --git a/django/db/models/signals.py b/django/db/models/signals.py index 2543cf5f4a..8c835e5f5f 100644 --- a/django/db/models/signals.py +++ b/django/db/models/signals.py @@ -1,6 +1,6 @@ from collections import defaultdict -from django.apps.cache import get_model +from django.apps import app_cache from django.dispatch import Signal from django.utils import six @@ -41,7 +41,7 @@ class ModelSignal(Signal): "Specified sender must either be a model or a " "model name of the 'app_label.ModelName' form." ) - sender = get_model(app_label, object_name, only_installed=False) + sender = app_cache.get_model(app_label, object_name, only_installed=False) if sender is None: reference = (app_label, object_name) self.unresolved_references[reference].append( diff --git a/django/db/utils.py b/django/db/utils.py index 43abaf9b5a..702b1b4ebc 100644 --- a/django/db/utils.py +++ b/django/db/utils.py @@ -282,6 +282,6 @@ class ConnectionRouter(object): """ Return app models allowed to be synchronized on provided db. """ - from .models import get_models - return [model for model in get_models(app, include_auto_created=include_auto_created) + from django.apps import app_cache + return [model for model in app_cache.get_models(app, include_auto_created=include_auto_created) if self.allow_migrate(db, model)] diff --git a/django/test/simple.py b/django/test/simple.py index 73deef917b..10f29061b3 100644 --- a/django/test/simple.py +++ b/django/test/simple.py @@ -9,7 +9,7 @@ import re import unittest as real_unittest import warnings -from django.db.models import get_app, get_apps +from django.apps import app_cache from django.test import _doctest as doctest from django.test import runner from django.test.utils import compare_xml, strip_quotes @@ -179,7 +179,7 @@ def build_test(label): # # First, look for TestCase instances with a name that matches # - app_module = get_app(parts[0]) + app_module = app_cache.get_app(parts[0]) test_module = get_tests(app_module) TestClass = getattr(app_module, parts[1], None) @@ -241,10 +241,10 @@ class DjangoTestSuiteRunner(runner.DiscoverRunner): if '.' in label: suite.addTest(build_test(label)) else: - app = get_app(label) + app = app_cache.get_app(label) suite.addTest(build_suite(app)) else: - for app in get_apps(): + for app in app_cache.get_apps(): suite.addTest(build_suite(app)) if extra_tests: diff --git a/django/test/testcases.py b/django/test/testcases.py index 52900ec478..1480889565 100644 --- a/django/test/testcases.py +++ b/django/test/testcases.py @@ -15,7 +15,7 @@ import unittest from unittest import skipIf # NOQA: Imported here for backward compatibility from unittest.util import safe_repr -from django.apps.cache import cache +from django.apps import app_cache from django.conf import settings from django.core import mail from django.core.exceptions import ValidationError, ImproperlyConfigured @@ -725,14 +725,14 @@ class TransactionTestCase(SimpleTestCase): """ super(TransactionTestCase, self)._pre_setup() if self.available_apps is not None: - cache.set_available_apps(self.available_apps) + app_cache.set_available_apps(self.available_apps) for db_name in self._databases_names(include_mirrors=False): flush.Command.emit_post_migrate(verbosity=0, interactive=False, database=db_name) try: self._fixture_setup() except Exception: if self.available_apps is not None: - cache.unset_available_apps() + app_cache.unset_available_apps() raise def _databases_names(self, include_mirrors=True): @@ -786,7 +786,7 @@ class TransactionTestCase(SimpleTestCase): for conn in connections.all(): conn.close() finally: - cache.unset_available_apps() + app_cache.unset_available_apps() def _fixture_teardown(self): # Allow TRUNCATE ... CASCADE and don't emit the post_migrate signal diff --git a/tests/app_cache/tests.py b/tests/app_cache/tests.py index 564f9f6f48..cc3637367b 100644 --- a/tests/app_cache/tests.py +++ b/tests/app_cache/tests.py @@ -1,6 +1,7 @@ from __future__ import absolute_import -from django.apps.cache import cache, BaseAppCache +from django.apps import app_cache +from django.apps.cache import BaseAppCache from django.db import models from django.test import TestCase @@ -16,8 +17,8 @@ class AppCacheTests(TestCase): """ Tests that the models in the models.py file were loaded correctly. """ - self.assertEqual(cache.get_model("app_cache", "TotallyNormal"), TotallyNormal) - self.assertEqual(cache.get_model("app_cache", "SoAlternative"), None) + self.assertEqual(app_cache.get_model("app_cache", "TotallyNormal"), TotallyNormal) + self.assertEqual(app_cache.get_model("app_cache", "SoAlternative"), None) self.assertEqual(new_app_cache.get_model("app_cache", "TotallyNormal"), None) self.assertEqual(new_app_cache.get_model("app_cache", "SoAlternative"), SoAlternative) @@ -26,7 +27,7 @@ class AppCacheTests(TestCase): """ Makes a new model at runtime and ensures it goes into the right place. """ - old_models = cache.get_models(cache.get_app("app_cache")) + old_models = app_cache.get_models(app_cache.get_app("app_cache")) # Construct a new model in a new app cache body = {} new_app_cache = BaseAppCache() @@ -41,6 +42,6 @@ class AppCacheTests(TestCase): # Make sure it appeared in the right place! self.assertEqual( old_models, - cache.get_models(cache.get_app("app_cache")), + app_cache.get_models(app_cache.get_app("app_cache")), ) self.assertEqual(new_app_cache.get_model("app_cache", "SouthPonies"), temp_model) diff --git a/tests/app_loading/tests.py b/tests/app_loading/tests.py index a8a5ba120f..b24522fab6 100644 --- a/tests/app_loading/tests.py +++ b/tests/app_loading/tests.py @@ -5,7 +5,8 @@ import os import sys from unittest import TestCase -from django.apps.cache import cache, load_app, get_model, get_models, AppCache +from django.apps import app_cache +from django.apps.cache import AppCache from django.test.utils import override_settings from django.utils._os import upath @@ -19,48 +20,48 @@ class EggLoadingTest(TestCase): # This test adds dummy applications to the app cache. These # need to be removed in order to prevent bad interactions # with the flush operation in other tests. - self.old_app_models = copy.deepcopy(cache.app_models) + self.old_app_models = copy.deepcopy(app_cache.app_models) def tearDown(self): sys.path = self.old_path - cache.app_models = self.old_app_models + app_cache.app_models = self.old_app_models def test_egg1(self): """Models module can be loaded from an app in an egg""" egg_name = '%s/modelapp.egg' % self.egg_dir sys.path.append(egg_name) - models = load_app('app_with_models') + models = app_cache.load_app('app_with_models') self.assertFalse(models is None) def test_egg2(self): """Loading an app from an egg that has no models returns no models (and no error)""" egg_name = '%s/nomodelapp.egg' % self.egg_dir sys.path.append(egg_name) - models = load_app('app_no_models') + models = app_cache.load_app('app_no_models') self.assertTrue(models is None) def test_egg3(self): """Models module can be loaded from an app located under an egg's top-level package""" egg_name = '%s/omelet.egg' % self.egg_dir sys.path.append(egg_name) - models = load_app('omelet.app_with_models') + models = app_cache.load_app('omelet.app_with_models') self.assertFalse(models is None) def test_egg4(self): """Loading an app with no models from under the top-level egg package generates no error""" egg_name = '%s/omelet.egg' % self.egg_dir sys.path.append(egg_name) - models = load_app('omelet.app_no_models') + models = app_cache.load_app('omelet.app_no_models') self.assertTrue(models is None) def test_egg5(self): """Loading an app from an egg that has an import error in its models module raises that error""" egg_name = '%s/brokenapp.egg' % self.egg_dir sys.path.append(egg_name) - self.assertRaises(ImportError, load_app, 'broken_app') + self.assertRaises(ImportError, app_cache.load_app, 'broken_app') raised = None try: - load_app('broken_app') + app_cache.load_app('broken_app') except ImportError as e: raised = e @@ -81,8 +82,8 @@ class EggLoadingTest(TestCase): a.loaded = False try: with override_settings(INSTALLED_APPS=('notexists',)): - self.assertRaises(ImportError, get_model, 'notexists', 'nomodel', seed_cache=True) - self.assertRaises(ImportError, get_model, 'notexists', 'nomodel', seed_cache=True) + self.assertRaises(ImportError, app_cache.get_model, 'notexists', 'nomodel', seed_cache=True) + self.assertRaises(ImportError, app_cache.get_model, 'notexists', 'nomodel', seed_cache=True) finally: a.loaded = True @@ -94,26 +95,26 @@ class GetModelsTest(TestCase): def test_get_model_only_returns_installed_models(self): self.assertEqual( - get_model("not_installed", "NotInstalledModel"), None) + app_cache.get_model("not_installed", "NotInstalledModel"), None) def test_get_model_with_not_installed(self): self.assertEqual( - get_model( + app_cache.get_model( "not_installed", "NotInstalledModel", only_installed=False), self.not_installed_module.NotInstalledModel) def test_get_models_only_returns_installed_models(self): self.assertFalse( "NotInstalledModel" in - [m.__name__ for m in get_models()]) + [m.__name__ for m in app_cache.get_models()]) def test_get_models_with_app_label_only_returns_installed_models(self): - self.assertEqual(get_models(self.not_installed_module), []) + self.assertEqual(app_cache.get_models(self.not_installed_module), []) def test_get_models_with_not_installed(self): self.assertTrue( "NotInstalledModel" in [ - m.__name__ for m in get_models(only_installed=False)]) + m.__name__ for m in app_cache.get_models(only_installed=False)]) class NotInstalledModelsTest(TestCase): diff --git a/tests/commands_sql/tests.py b/tests/commands_sql/tests.py index 3a0b5527f4..82e55d9861 100644 --- a/tests/commands_sql/tests.py +++ b/tests/commands_sql/tests.py @@ -1,9 +1,10 @@ from __future__ import unicode_literals +from django.apps import app_cache from django.core.management.color import no_style from django.core.management.sql import (sql_create, sql_delete, sql_indexes, sql_destroy_indexes, sql_all) -from django.db import connections, DEFAULT_DB_ALIAS, models, router +from django.db import connections, DEFAULT_DB_ALIAS, router from django.test import TestCase from django.utils import six @@ -16,7 +17,7 @@ class SQLCommandsTestCase(TestCase): return len([o for o in output if o.startswith(cmd)]) def test_sql_create(self): - app = models.get_app('commands_sql') + app = app_cache.get_app('commands_sql') output = sql_create(app, no_style(), connections[DEFAULT_DB_ALIAS]) create_tables = [o for o in output if o.startswith('CREATE TABLE')] self.assertEqual(len(create_tables), 3) @@ -25,7 +26,7 @@ class SQLCommandsTestCase(TestCase): six.assertRegex(self, sql, r'^create table .commands_sql_book.*') def test_sql_delete(self): - app = models.get_app('commands_sql') + app = app_cache.get_app('commands_sql') output = sql_delete(app, no_style(), connections[DEFAULT_DB_ALIAS]) drop_tables = [o for o in output if o.startswith('DROP TABLE')] self.assertEqual(len(drop_tables), 3) @@ -34,19 +35,19 @@ class SQLCommandsTestCase(TestCase): six.assertRegex(self, sql, r'^drop table .commands_sql_comment.*') def test_sql_indexes(self): - app = models.get_app('commands_sql') + app = app_cache.get_app('commands_sql') output = sql_indexes(app, no_style(), connections[DEFAULT_DB_ALIAS]) # PostgreSQL creates one additional index for CharField self.assertIn(self.count_ddl(output, 'CREATE INDEX'), [3, 4]) def test_sql_destroy_indexes(self): - app = models.get_app('commands_sql') + app = app_cache.get_app('commands_sql') output = sql_destroy_indexes(app, no_style(), connections[DEFAULT_DB_ALIAS]) # PostgreSQL creates one additional index for CharField self.assertIn(self.count_ddl(output, 'DROP INDEX'), [3, 4]) def test_sql_all(self): - app = models.get_app('commands_sql') + app = app_cache.get_app('commands_sql') output = sql_all(app, no_style(), connections[DEFAULT_DB_ALIAS]) self.assertEqual(self.count_ddl(output, 'CREATE TABLE'), 3) @@ -68,7 +69,7 @@ class SQLCommandsRouterTestCase(TestCase): router.routers = self._old_routers def test_router_honored(self): - app = models.get_app('commands_sql') + app = app_cache.get_app('commands_sql') for sql_command in (sql_all, sql_create, sql_delete, sql_indexes, sql_destroy_indexes): output = sql_command(app, no_style(), connections[DEFAULT_DB_ALIAS]) self.assertEqual(len(output), 0, diff --git a/tests/defer_regress/tests.py b/tests/defer_regress/tests.py index 0107e8167c..794ea6e18e 100644 --- a/tests/defer_regress/tests.py +++ b/tests/defer_regress/tests.py @@ -2,7 +2,7 @@ from __future__ import unicode_literals from operator import attrgetter -from django.apps.cache import cache +from django.apps import app_cache from django.contrib.contenttypes.models import ContentType from django.contrib.sessions.backends.db import SessionStore from django.db.models import Count @@ -103,7 +103,7 @@ class DeferRegressionTest(TestCase): klasses = set( map( attrgetter("__name__"), - cache.get_models(cache.get_app("defer_regress")) + app_cache.get_models(app_cache.get_app("defer_regress")) ) ) self.assertIn("Child", klasses) @@ -111,13 +111,13 @@ class DeferRegressionTest(TestCase): self.assertNotIn("Child_Deferred_value", klasses) self.assertNotIn("Item_Deferred_name", klasses) self.assertFalse(any( - k._deferred for k in cache.get_models(cache.get_app("defer_regress")))) + k._deferred for k in app_cache.get_models(app_cache.get_app("defer_regress")))) klasses_with_deferred = set( map( attrgetter("__name__"), - cache.get_models( - cache.get_app("defer_regress"), include_deferred=True + app_cache.get_models( + app_cache.get_app("defer_regress"), include_deferred=True ), ) ) @@ -126,8 +126,8 @@ class DeferRegressionTest(TestCase): self.assertIn("Child_Deferred_value", klasses_with_deferred) self.assertIn("Item_Deferred_name", klasses_with_deferred) self.assertTrue(any( - k._deferred for k in cache.get_models( - cache.get_app("defer_regress"), include_deferred=True)) + k._deferred for k in app_cache.get_models( + app_cache.get_app("defer_regress"), include_deferred=True)) ) @override_settings(SESSION_SERIALIZER='django.contrib.sessions.serializers.PickleSerializer') diff --git a/tests/empty/tests.py b/tests/empty/tests.py index 2a9f568aea..b8476fc73d 100644 --- a/tests/empty/tests.py +++ b/tests/empty/tests.py @@ -1,4 +1,4 @@ -from django.apps.cache import get_app +from django.apps import app_cache from django.core.exceptions import ImproperlyConfigured from django.test import TestCase from django.test.utils import override_settings @@ -33,4 +33,4 @@ class NoModelTests(TestCase): def test_no_models(self): with six.assertRaisesRegex(self, ImproperlyConfigured, 'App with label no_models is missing a models.py module.'): - get_app('no_models') + app_cache.get_app('no_models') diff --git a/tests/invalid_models/tests.py b/tests/invalid_models/tests.py index 46b3dc4c2e..abb7d9b33d 100644 --- a/tests/invalid_models/tests.py +++ b/tests/invalid_models/tests.py @@ -2,7 +2,7 @@ import copy import sys import unittest -from django.apps.cache import cache, load_app +from django.apps import app_cache from django.core.management.validation import get_validation_errors from django.test.utils import override_settings from django.utils.six import StringIO @@ -22,11 +22,11 @@ class InvalidModelTestCase(unittest.TestCase): # This test adds dummy applications to the app cache. These # need to be removed in order to prevent bad interactions # with the flush operation in other tests. - self.old_app_models = copy.deepcopy(cache.app_models) + self.old_app_models = copy.deepcopy(app_cache.app_models) def tearDown(self): - cache.app_models = self.old_app_models - cache._get_models_cache = {} + app_cache.app_models = self.old_app_models + app_cache._get_models_cache = {} sys.stdout = self.old_stdout # Technically, this isn't an override -- TEST_SWAPPED_MODEL must be @@ -40,7 +40,7 @@ class InvalidModelTestCase(unittest.TestCase): ) def test_invalid_models(self): try: - module = load_app("invalid_models.invalid_models") + module = app_cache.load_app("invalid_models.invalid_models") except Exception: self.fail('Unable to load invalid model module') diff --git a/tests/managers_regress/tests.py b/tests/managers_regress/tests.py index 25717f7431..de9f72c333 100644 --- a/tests/managers_regress/tests.py +++ b/tests/managers_regress/tests.py @@ -1,7 +1,7 @@ from __future__ import unicode_literals import copy -from django.apps.cache import cache +from django.apps import app_cache from django.db import models from django.template import Context, Template from django.test import TestCase @@ -114,7 +114,7 @@ class ManagersRegressionTests(TestCase): # This test adds dummy models to the app cache. These # need to be removed in order to prevent bad interactions # with the flush operation in other tests. - old_app_models = copy.deepcopy(cache.app_models) + old_app_models = copy.deepcopy(app_cache.app_models) class SwappableModel(models.Model): class Meta: @@ -129,7 +129,7 @@ class ManagersRegressionTests(TestCase): self.assertEqual(str(e), "Manager isn't available; SwappableModel has been swapped for 'managers_regress.Parent'") finally: - cache.app_models = old_app_models + app_cache.app_models = old_app_models @override_settings(TEST_SWAPPABLE_MODEL='managers_regress.Parent') def test_custom_swappable_manager(self): @@ -137,7 +137,7 @@ class ManagersRegressionTests(TestCase): # This test adds dummy models to the app cache. These # need to be removed in order to prevent bad interactions # with the flush operation in other tests. - old_app_models = copy.deepcopy(cache.app_models) + old_app_models = copy.deepcopy(app_cache.app_models) class SwappableModel(models.Model): @@ -156,7 +156,7 @@ class ManagersRegressionTests(TestCase): self.assertEqual(str(e), "Manager isn't available; SwappableModel has been swapped for 'managers_regress.Parent'") finally: - cache.app_models = old_app_models + app_cache.app_models = old_app_models @override_settings(TEST_SWAPPABLE_MODEL='managers_regress.Parent') def test_explicit_swappable_manager(self): @@ -164,7 +164,7 @@ class ManagersRegressionTests(TestCase): # This test adds dummy models to the app cache. These # need to be removed in order to prevent bad interactions # with the flush operation in other tests. - old_app_models = copy.deepcopy(cache.app_models) + old_app_models = copy.deepcopy(app_cache.app_models) class SwappableModel(models.Model): @@ -183,7 +183,7 @@ class ManagersRegressionTests(TestCase): self.assertEqual(str(e), "Manager isn't available; SwappableModel has been swapped for 'managers_regress.Parent'") finally: - cache.app_models = old_app_models + app_cache.app_models = old_app_models def test_regress_3871(self): related = RelatedModel.objects.create() diff --git a/tests/migrations/test_commands.py b/tests/migrations/test_commands.py index 9d84d710bb..08b7371301 100644 --- a/tests/migrations/test_commands.py +++ b/tests/migrations/test_commands.py @@ -6,7 +6,7 @@ import copy import os import shutil -from django.apps.cache import cache +from django.apps import app_cache from django.core.management import call_command, CommandError from django.test.utils import override_settings from django.utils import six @@ -132,11 +132,11 @@ class MakeMigrationsTests(MigrationTestBase): self.test_dir = os.path.abspath(os.path.dirname(upath(__file__))) self.migration_dir = os.path.join(self.test_dir, 'migrations_%d' % self.creation_counter) self.migration_pkg = "migrations.migrations_%d" % self.creation_counter - self._old_app_models = copy.deepcopy(cache.app_models) + self._old_app_models = copy.deepcopy(app_cache.app_models) def tearDown(self): - cache.app_models = self._old_app_models - cache._get_models_cache = {} + app_cache.app_models = self._old_app_models + app_cache._get_models_cache = {} os.chdir(self.test_dir) try: @@ -152,7 +152,7 @@ class MakeMigrationsTests(MigrationTestBase): def test_files_content(self): self.assertTableNotExists("migrations_unicodemodel") - cache.register_models('migrations', UnicodeModel) + app_cache.register_models('migrations', UnicodeModel) with override_settings(MIGRATION_MODULES={"migrations": self.migration_pkg}): call_command("makemigrations", "migrations", verbosity=0) @@ -188,7 +188,7 @@ class MakeMigrationsTests(MigrationTestBase): def test_failing_migration(self): #21280 - If a migration fails to serialize, it shouldn't generate an empty file. - cache.register_models('migrations', UnserializableModel) + app_cache.register_models('migrations', UnserializableModel) with six.assertRaisesRegex(self, ValueError, r'Cannot serialize'): with override_settings(MIGRATION_MODULES={"migrations": self.migration_pkg}): diff --git a/tests/migrations/test_operations.py b/tests/migrations/test_operations.py index 20aff59de2..d844d36c39 100644 --- a/tests/migrations/test_operations.py +++ b/tests/migrations/test_operations.py @@ -1,4 +1,5 @@ import unittest +from django.apps import app_cache from django.db import connection, models, migrations, router from django.db.models.fields import NOT_PROVIDED from django.db.transaction import atomic @@ -203,8 +204,8 @@ class OperationTests(MigrationTestBase): self.assertColumnNotExists("test_adflmm_pony", "stables") # Make sure the M2M field actually works with atomic(): - app_cache = new_state.render() - Pony = app_cache.get_model("test_adflmm", "Pony") + new_app_cache = new_state.render() + Pony = new_app_cache.get_model("test_adflmm", "Pony") p = Pony.objects.create(pink=False, weight=4.55) p.stables.create() self.assertEqual(p.stables.count(), 1) diff --git a/tests/migrations/test_writer.py b/tests/migrations/test_writer.py index cc32a7d751..960af90eaa 100644 --- a/tests/migrations/test_writer.py +++ b/tests/migrations/test_writer.py @@ -5,7 +5,7 @@ from __future__ import unicode_literals import datetime import os -from django.apps.cache import cache +from django.apps import app_cache from django.core.validators import RegexValidator, EmailValidator from django.db import models, migrations from django.db.migrations.writer import MigrationWriter @@ -124,7 +124,7 @@ class WriterTests(TestCase): with override_settings(INSTALLED_APPS=test_apps): for app in test_apps: - cache.load_app(app) + app_cache.load_app(app) migration = migrations.Migration('0001_initial', app.split('.')[-1]) expected_path = os.path.join(base_dir, *(app.split('.') + ['migrations', '0001_initial.py'])) writer = MigrationWriter(migration) diff --git a/tests/proxy_model_inheritance/tests.py b/tests/proxy_model_inheritance/tests.py index 0fad8c594f..23058d122b 100644 --- a/tests/proxy_model_inheritance/tests.py +++ b/tests/proxy_model_inheritance/tests.py @@ -3,7 +3,7 @@ from __future__ import unicode_literals import os import sys -from django.apps.cache import cache, load_app +from django.apps import app_cache from django.conf import settings from django.core.management import call_command from django.test import TestCase, TransactionTestCase @@ -28,21 +28,21 @@ class ProxyModelInheritanceTests(TransactionTestCase): self.old_sys_path = sys.path[:] sys.path.append(os.path.dirname(os.path.abspath(upath(__file__)))) for app in settings.INSTALLED_APPS: - load_app(app) + app_cache.load_app(app) def tearDown(self): sys.path = self.old_sys_path - del cache.app_labels['app1'] - del cache.app_labels['app2'] - del cache.app_models['app1'] - del cache.app_models['app2'] + del app_cache.app_labels['app1'] + del app_cache.app_labels['app2'] + del app_cache.app_models['app1'] + del app_cache.app_models['app2'] def test_table_exists(self): try: - cache.set_available_apps(settings.INSTALLED_APPS) + app_cache.set_available_apps(settings.INSTALLED_APPS) call_command('migrate', verbosity=0) finally: - cache.unset_available_apps() + app_cache.unset_available_apps() from .app1.models import ProxyModel from .app2.models import NiceModel self.assertEqual(NiceModel.objects.all().count(), 0) diff --git a/tests/proxy_models/tests.py b/tests/proxy_models/tests.py index 5b9433bbf7..cdd979a399 100644 --- a/tests/proxy_models/tests.py +++ b/tests/proxy_models/tests.py @@ -1,7 +1,7 @@ from __future__ import unicode_literals import copy -from django.apps.cache import cache +from django.apps import app_cache from django.contrib import admin from django.contrib.contenttypes.models import ContentType from django.core import management @@ -159,7 +159,7 @@ class ProxyModelTests(TestCase): # This test adds dummy applications to the app cache. These # need to be removed in order to prevent bad interactions # with the flush operation in other tests. - old_app_models = copy.deepcopy(cache.app_models) + old_app_models = copy.deepcopy(app_cache.app_models) class SwappableModel(models.Model): @@ -176,7 +176,7 @@ class ProxyModelTests(TestCase): class Meta: proxy = True finally: - cache.app_models = old_app_models + app_cache.app_models = old_app_models def test_myperson_manager(self): Person.objects.create(name="fred") diff --git a/tests/runtests.py b/tests/runtests.py index 8bcb06e522..9ef81f8877 100755 --- a/tests/runtests.py +++ b/tests/runtests.py @@ -80,13 +80,13 @@ def get_test_modules(): def get_installed(): - from django.apps.cache import get_apps - return [app.__name__.rsplit('.', 1)[0] for app in get_apps()] + from django.apps import app_cache + return [app.__name__.rsplit('.', 1)[0] for app in app_cache.get_apps()] def setup(verbosity, test_labels): import django - from django.apps.cache import get_apps, load_app + from django.apps import app_cache from django.conf import settings from django.test import TransactionTestCase, TestCase @@ -128,7 +128,7 @@ def setup(verbosity, test_labels): # Load all the ALWAYS_INSTALLED_APPS. with warnings.catch_warnings(): warnings.filterwarnings('ignore', 'django.contrib.comments is deprecated and will be removed before Django 1.8.', DeprecationWarning) - get_apps() + app_cache.get_apps() # Load all the test model apps. test_modules = get_test_modules() @@ -164,7 +164,7 @@ def setup(verbosity, test_labels): if module_found_in_labels: if verbosity >= 2: print("Importing application %s" % module_name) - mod = load_app(module_label) + mod = app_cache.load_app(module_label) if mod: if module_label not in settings.INSTALLED_APPS: settings.INSTALLED_APPS.append(module_label) diff --git a/tests/swappable_models/tests.py b/tests/swappable_models/tests.py index ae42366745..0beb95af3e 100644 --- a/tests/swappable_models/tests.py +++ b/tests/swappable_models/tests.py @@ -2,7 +2,7 @@ from __future__ import unicode_literals from django.utils.six import StringIO -from django.apps.cache import cache +from django.apps import app_cache from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType from django.core import management @@ -23,12 +23,12 @@ class SwappableModelTests(TestCase): def setUp(self): # This test modifies the installed apps, so we need to make sure # we're not dealing with a cached app list. - cache._get_models_cache.clear() + app_cache._get_models_cache.clear() def tearDown(self): # By fiddling with swappable models, we alter the installed models # cache, so flush it to make sure there are no side effects. - cache._get_models_cache.clear() + app_cache._get_models_cache.clear() @override_settings(TEST_ARTICLE_MODEL='swappable_models.AlternateArticle') def test_generated_data(self): diff --git a/tests/tablespaces/tests.py b/tests/tablespaces/tests.py index 04240bcaa1..9bcfed05ed 100644 --- a/tests/tablespaces/tests.py +++ b/tests/tablespaces/tests.py @@ -2,7 +2,7 @@ from __future__ import unicode_literals import copy -from django.apps.cache import cache +from django.apps import app_cache from django.conf import settings from django.db import connection from django.core.management.color import no_style @@ -28,7 +28,7 @@ class TablespacesTests(TestCase): def setUp(self): # The unmanaged models need to be removed after the test in order to # prevent bad interactions with the flush operation in other tests. - self.old_app_models = copy.deepcopy(cache.app_models) + self.old_app_models = copy.deepcopy(app_cache.app_models) for model in Article, Authors, Reviewers, Scientist: model._meta.managed = True @@ -37,8 +37,8 @@ class TablespacesTests(TestCase): for model in Article, Authors, Reviewers, Scientist: model._meta.managed = False - cache.app_models = self.old_app_models - cache._get_models_cache = {} + app_cache.app_models = self.old_app_models + app_cache._get_models_cache = {} def assertNumContains(self, haystack, needle, count): real_count = haystack.count(needle) diff --git a/tests/test_suite_override/tests.py b/tests/test_suite_override/tests.py index e69dab12bf..ed336076e7 100644 --- a/tests/test_suite_override/tests.py +++ b/tests/test_suite_override/tests.py @@ -1,6 +1,6 @@ import unittest -from django.db.models import get_app +from django.apps import app_cache from django.test.utils import IgnoreAllDeprecationWarningsMixin @@ -20,7 +20,7 @@ class SuiteOverrideTest(IgnoreAllDeprecationWarningsMixin, unittest.TestCase): """ from django.test.simple import build_suite - app = get_app("test_suite_override") + app = app_cache.get_app("test_suite_override") suite = build_suite(app) self.assertEqual(suite.countTestCases(), 1)