Deprecated get_app().

This commit is contained in:
Aymeric Augustin 2013-12-14 11:11:52 +01:00
parent 2732edc5f2
commit 69039becde
13 changed files with 55 additions and 62 deletions

View File

@ -189,19 +189,6 @@ class BaseAppCache(object):
raise UnavailableApp("App with label %r isn't available." % app_label) raise UnavailableApp("App with label %r isn't available." % app_label)
return app_config return app_config
def get_app(self, app_label):
"""
Returns the module containing the models for the given app_label.
Raises UnavailableApp when set_available_apps() in in effect and
doesn't include app_label.
"""
try:
return self.get_app_config(app_label).models_module
except LookupError as exc:
# Change the exception type for backwards compatibility.
raise ImproperlyConfigured(*exc.args)
def get_models(self, app_mod=None, def get_models(self, app_mod=None,
include_auto_created=False, include_deferred=False, include_auto_created=False, include_deferred=False,
only_installed=True, include_swapped=False): only_installed=True, include_swapped=False):
@ -332,6 +319,22 @@ class BaseAppCache(object):
### DEPRECATED METHODS GO BELOW THIS LINE ### ### DEPRECATED METHODS GO BELOW THIS LINE ###
def get_app(self, app_label):
"""
Returns the module containing the models for the given app_label.
Raises UnavailableApp when set_available_apps() in in effect and
doesn't include app_label.
"""
warnings.warn(
"get_app_config(app_label).models_module supersedes get_app(app_label).",
PendingDeprecationWarning, stacklevel=2)
try:
return self.get_app_config(app_label).models_module
except LookupError as exc:
# Change the exception type for backwards compatibility.
raise ImproperlyConfigured(*exc.args)
def get_apps(self): def get_apps(self):
""" """
Returns a list of all installed modules that contain models. Returns a list of all installed modules that contain models.

View File

@ -9,7 +9,7 @@ from django.conf import settings
from django.contrib import admin from django.contrib import admin
from django.contrib.admin.views.decorators import staff_member_required from django.contrib.admin.views.decorators import staff_member_required
from django.db import models from django.db import models
from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist from django.core.exceptions import ViewDoesNotExist
from django.http import Http404 from django.http import Http404
from django.core import urlresolvers from django.core import urlresolvers
from django.contrib.admindocs import utils from django.contrib.admindocs import utils
@ -194,17 +194,12 @@ class ModelDetailView(BaseAdminDocsView):
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
# Get the model class. # Get the model class.
try: try:
app_mod = app_cache.get_app(self.kwargs['app_label']) app_cache.get_app_config(self.kwargs['app_label'])
except ImproperlyConfigured: except LookupError:
raise Http404(_("App %r not found") % self.kwargs['app_label']) raise Http404(_("App %(app_label)r not found") % self.kwargs)
model = None model = app_cache.get_model(self.kwargs['app_label'], self.kwargs['model_name'])
for m in app_cache.get_models(app_mod):
if m._meta.model_name == self.kwargs['model_name']:
model = m
break
if model is None: if model is None:
raise Http404(_("Model %(model_name)r not found in app %(app_label)r") % { raise Http404(_("Model %(model_name)r not found in app %(app_label)r") % self.kwargs)
'model_name': self.kwargs['model_name'], 'app_label': self.kwargs['app_label']})
opts = model._meta opts = model._meta

View File

@ -184,21 +184,21 @@ class CustomUserModelValidationTestCase(TestCase):
def test_required_fields_is_list(self): def test_required_fields_is_list(self):
"REQUIRED_FIELDS should be a list." "REQUIRED_FIELDS should be a list."
new_io = StringIO() new_io = StringIO()
get_validation_errors(new_io, app_cache.get_app('auth')) get_validation_errors(new_io, app_cache.get_app_config('auth').models_module)
self.assertIn("The REQUIRED_FIELDS must be a list or tuple.", new_io.getvalue()) self.assertIn("The REQUIRED_FIELDS must be a list or tuple.", new_io.getvalue())
@override_settings(AUTH_USER_MODEL='auth.CustomUserBadRequiredFields') @override_settings(AUTH_USER_MODEL='auth.CustomUserBadRequiredFields')
def test_username_not_in_required_fields(self): def test_username_not_in_required_fields(self):
"USERNAME_FIELD should not appear in REQUIRED_FIELDS." "USERNAME_FIELD should not appear in REQUIRED_FIELDS."
new_io = StringIO() new_io = StringIO()
get_validation_errors(new_io, app_cache.get_app('auth')) get_validation_errors(new_io, app_cache.get_app_config('auth').models_module)
self.assertIn("The field named as the USERNAME_FIELD should not be included in REQUIRED_FIELDS on a swappable User model.", new_io.getvalue()) 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') @override_settings(AUTH_USER_MODEL='auth.CustomUserNonUniqueUsername')
def test_username_non_unique(self): def test_username_non_unique(self):
"A non-unique USERNAME_FIELD should raise a model validation error." "A non-unique USERNAME_FIELD should raise a model validation error."
new_io = StringIO() new_io = StringIO()
get_validation_errors(new_io, app_cache.get_app('auth')) get_validation_errors(new_io, app_cache.get_app_config('auth').models_module)
self.assertIn("The USERNAME_FIELD must be unique. Add unique=True to the field parameters.", new_io.getvalue()) self.assertIn("The USERNAME_FIELD must be unique. Add unique=True to the field parameters.", new_io.getvalue())

View File

@ -11,7 +11,6 @@ import sys
from optparse import make_option, OptionParser from optparse import make_option, OptionParser
import django import django
from django.core.exceptions import ImproperlyConfigured
from django.core.management.color import color_style, no_style from django.core.management.color import color_style, no_style
from django.utils.encoding import force_str from django.utils.encoding import force_str
from django.utils.six import StringIO from django.utils.six import StringIO
@ -346,8 +345,8 @@ class AppCommand(BaseCommand):
if not app_labels: if not app_labels:
raise CommandError('Enter at least one appname.') raise CommandError('Enter at least one appname.')
try: try:
app_list = [app_cache.get_app(app_label) for app_label in app_labels] app_list = [app_cache.get_app_config(app_label).models_module for app_label in app_labels]
except (ImproperlyConfigured, ImportError) as e: except (LookupError, ImportError) as e:
raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e) raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e)
output = [] output = []
for app in app_list: for app in app_list:

View File

@ -3,7 +3,6 @@ import warnings
from collections import OrderedDict from collections import OrderedDict
from optparse import make_option from optparse import make_option
from django.core.exceptions import ImproperlyConfigured
from django.core.management.base import BaseCommand, CommandError from django.core.management.base import BaseCommand, CommandError
from django.core import serializers from django.core import serializers
from django.db import router, DEFAULT_DB_ALIAS from django.db import router, DEFAULT_DB_ALIAS
@ -70,9 +69,9 @@ class Command(BaseCommand):
excluded_models.add(model_obj) excluded_models.add(model_obj)
else: else:
try: try:
app_obj = app_cache.get_app(exclude) app_obj = app_cache.get_app_config(exclude).models_module
excluded_apps.add(app_obj) excluded_apps.add(app_obj)
except ImproperlyConfigured: except LookupError:
raise CommandError('Unknown app in excludes: %s' % exclude) raise CommandError('Unknown app in excludes: %s' % exclude)
if len(app_labels) == 0: if len(app_labels) == 0:
@ -89,8 +88,8 @@ class Command(BaseCommand):
try: try:
app_label, model_label = label.split('.') app_label, model_label = label.split('.')
try: try:
app = app_cache.get_app(app_label) app = app_cache.get_app_config(app_label).models_module
except ImproperlyConfigured: except LookupError:
raise CommandError("Unknown application: %s" % app_label) raise CommandError("Unknown application: %s" % app_label)
if app in excluded_apps: if app in excluded_apps:
continue continue
@ -109,8 +108,8 @@ class Command(BaseCommand):
# This is just an app - no model qualifier # This is just an app - no model qualifier
app_label = label app_label = label
try: try:
app = app_cache.get_app(app_label) app = app_cache.get_app_config(app_label).models_module
except ImproperlyConfigured: except LookupError:
raise CommandError("Unknown application: %s" % app_label) raise CommandError("Unknown application: %s" % app_label)
if app in excluded_apps: if app in excluded_apps:
continue continue

View File

@ -5,7 +5,6 @@ from optparse import make_option
from django.apps import app_cache from django.apps import app_cache
from django.core.management.base import BaseCommand, CommandError from django.core.management.base import BaseCommand, CommandError
from django.core.exceptions import ImproperlyConfigured
from django.db import connections, DEFAULT_DB_ALIAS, migrations from django.db import connections, DEFAULT_DB_ALIAS, migrations
from django.db.migrations.loader import MigrationLoader from django.db.migrations.loader import MigrationLoader
from django.db.migrations.autodetector import MigrationAutodetector from django.db.migrations.autodetector import MigrationAutodetector
@ -38,8 +37,8 @@ class Command(BaseCommand):
bad_app_labels = set() bad_app_labels = set()
for app_label in app_labels: for app_label in app_labels:
try: try:
app_cache.get_app(app_label) app_cache.get_app_config(app_label)
except ImproperlyConfigured: except LookupError:
bad_app_labels.add(app_label) bad_app_labels.add(app_label)
if bad_app_labels: if bad_app_labels:
for app_label in bad_app_labels: for app_label in bad_app_labels:

View File

@ -5,7 +5,6 @@ import sys
from django.apps import app_cache from django.apps import app_cache
from django.utils import datetime_safe from django.utils import datetime_safe
from django.utils.six.moves import input from django.utils.six.moves import input
from django.core.exceptions import ImproperlyConfigured
class MigrationQuestioner(object): class MigrationQuestioner(object):
@ -29,10 +28,10 @@ class MigrationQuestioner(object):
# Apps from the new app template will have these; the python # Apps from the new app template will have these; the python
# file check will ensure we skip South ones. # file check will ensure we skip South ones.
try: try:
models_module = app_cache.get_app(app_label) app_config = app_cache.get_app_config(app_label)
except ImproperlyConfigured: # It's a fake app except LookupError: # It's a fake app.
return self.defaults.get("ask_initial", False) return self.defaults.get("ask_initial", False)
migrations_import_path = "%s.migrations" % models_module.__package__ migrations_import_path = "%s.migrations" % app_config.name
try: try:
migrations_module = importlib.import_module(migrations_import_path) migrations_module = importlib.import_module(migrations_import_path)
except ImportError: except ImportError:

View File

@ -179,7 +179,7 @@ def build_test(label):
# #
# First, look for TestCase instances with a name that matches # First, look for TestCase instances with a name that matches
# #
app_module = app_cache.get_app(parts[0]) app_module = app_cache.get_app_config(parts[0]).models_module
test_module = get_tests(app_module) test_module = get_tests(app_module)
TestClass = getattr(app_module, parts[1], None) TestClass = getattr(app_module, parts[1], None)
@ -241,7 +241,7 @@ class DjangoTestSuiteRunner(runner.DiscoverRunner):
if '.' in label: if '.' in label:
suite.addTest(build_test(label)) suite.addTest(build_test(label))
else: else:
app = app_cache.get_app(label) app = app_cache.get_app_config(label).models_module
suite.addTest(build_suite(app)) suite.addTest(build_suite(app))
else: else:
for app_config in app_cache.get_app_configs(): for app_config in app_cache.get_app_configs():

View File

@ -27,7 +27,7 @@ class AppCacheTests(TestCase):
""" """
Makes a new model at runtime and ensures it goes into the right place. Makes a new model at runtime and ensures it goes into the right place.
""" """
old_models = app_cache.get_models(app_cache.get_app("app_cache")) old_models = app_cache.get_models(app_cache.get_app_config("app_cache").models_module)
# Construct a new model in a new app cache # Construct a new model in a new app cache
body = {} body = {}
new_app_cache = BaseAppCache() new_app_cache = BaseAppCache()
@ -42,6 +42,6 @@ class AppCacheTests(TestCase):
# Make sure it appeared in the right place! # Make sure it appeared in the right place!
self.assertEqual( self.assertEqual(
old_models, old_models,
app_cache.get_models(app_cache.get_app("app_cache")), app_cache.get_models(app_cache.get_app_config("app_cache").models_module),
) )
self.assertEqual(new_app_cache.get_model("app_cache", "SouthPonies"), temp_model) self.assertEqual(new_app_cache.get_model("app_cache", "SouthPonies"), temp_model)

View File

@ -17,7 +17,7 @@ class SQLCommandsTestCase(TestCase):
return len([o for o in output if o.startswith(cmd)]) return len([o for o in output if o.startswith(cmd)])
def test_sql_create(self): def test_sql_create(self):
app = app_cache.get_app('commands_sql') app = app_cache.get_app_config('commands_sql').models_module
output = sql_create(app, no_style(), connections[DEFAULT_DB_ALIAS]) output = sql_create(app, no_style(), connections[DEFAULT_DB_ALIAS])
create_tables = [o for o in output if o.startswith('CREATE TABLE')] create_tables = [o for o in output if o.startswith('CREATE TABLE')]
self.assertEqual(len(create_tables), 3) self.assertEqual(len(create_tables), 3)
@ -26,7 +26,7 @@ class SQLCommandsTestCase(TestCase):
six.assertRegex(self, sql, r'^create table .commands_sql_book.*') six.assertRegex(self, sql, r'^create table .commands_sql_book.*')
def test_sql_delete(self): def test_sql_delete(self):
app = app_cache.get_app('commands_sql') app = app_cache.get_app_config('commands_sql').models_module
output = sql_delete(app, no_style(), connections[DEFAULT_DB_ALIAS]) output = sql_delete(app, no_style(), connections[DEFAULT_DB_ALIAS])
drop_tables = [o for o in output if o.startswith('DROP TABLE')] drop_tables = [o for o in output if o.startswith('DROP TABLE')]
self.assertEqual(len(drop_tables), 3) self.assertEqual(len(drop_tables), 3)
@ -35,19 +35,19 @@ class SQLCommandsTestCase(TestCase):
six.assertRegex(self, sql, r'^drop table .commands_sql_comment.*') six.assertRegex(self, sql, r'^drop table .commands_sql_comment.*')
def test_sql_indexes(self): def test_sql_indexes(self):
app = app_cache.get_app('commands_sql') app = app_cache.get_app_config('commands_sql').models_module
output = sql_indexes(app, no_style(), connections[DEFAULT_DB_ALIAS]) output = sql_indexes(app, no_style(), connections[DEFAULT_DB_ALIAS])
# PostgreSQL creates one additional index for CharField # PostgreSQL creates one additional index for CharField
self.assertIn(self.count_ddl(output, 'CREATE INDEX'), [3, 4]) self.assertIn(self.count_ddl(output, 'CREATE INDEX'), [3, 4])
def test_sql_destroy_indexes(self): def test_sql_destroy_indexes(self):
app = app_cache.get_app('commands_sql') app = app_cache.get_app_config('commands_sql').models_module
output = sql_destroy_indexes(app, no_style(), connections[DEFAULT_DB_ALIAS]) output = sql_destroy_indexes(app, no_style(), connections[DEFAULT_DB_ALIAS])
# PostgreSQL creates one additional index for CharField # PostgreSQL creates one additional index for CharField
self.assertIn(self.count_ddl(output, 'DROP INDEX'), [3, 4]) self.assertIn(self.count_ddl(output, 'DROP INDEX'), [3, 4])
def test_sql_all(self): def test_sql_all(self):
app = app_cache.get_app('commands_sql') app = app_cache.get_app_config('commands_sql').models_module
output = sql_all(app, no_style(), connections[DEFAULT_DB_ALIAS]) output = sql_all(app, no_style(), connections[DEFAULT_DB_ALIAS])
self.assertEqual(self.count_ddl(output, 'CREATE TABLE'), 3) self.assertEqual(self.count_ddl(output, 'CREATE TABLE'), 3)
@ -69,7 +69,7 @@ class SQLCommandsRouterTestCase(TestCase):
router.routers = self._old_routers router.routers = self._old_routers
def test_router_honored(self): def test_router_honored(self):
app = app_cache.get_app('commands_sql') app = app_cache.get_app_config('commands_sql').models_module
for sql_command in (sql_all, sql_create, sql_delete, sql_indexes, sql_destroy_indexes): 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]) output = sql_command(app, no_style(), connections[DEFAULT_DB_ALIAS])
self.assertEqual(len(output), 0, self.assertEqual(len(output), 0,

View File

@ -103,7 +103,7 @@ class DeferRegressionTest(TestCase):
klasses = set( klasses = set(
map( map(
attrgetter("__name__"), attrgetter("__name__"),
app_cache.get_models(app_cache.get_app("defer_regress")) app_cache.get_models(app_cache.get_app_config("defer_regress").models_module)
) )
) )
self.assertIn("Child", klasses) self.assertIn("Child", klasses)
@ -111,13 +111,13 @@ class DeferRegressionTest(TestCase):
self.assertNotIn("Child_Deferred_value", klasses) self.assertNotIn("Child_Deferred_value", klasses)
self.assertNotIn("Item_Deferred_name", klasses) self.assertNotIn("Item_Deferred_name", klasses)
self.assertFalse(any( self.assertFalse(any(
k._deferred for k in app_cache.get_models(app_cache.get_app("defer_regress")))) k._deferred for k in app_cache.get_models(app_cache.get_app_config("defer_regress").models_module)))
klasses_with_deferred = set( klasses_with_deferred = set(
map( map(
attrgetter("__name__"), attrgetter("__name__"),
app_cache.get_models( app_cache.get_models(
app_cache.get_app("defer_regress"), include_deferred=True app_cache.get_app_config("defer_regress").models_module, include_deferred=True
), ),
) )
) )
@ -127,7 +127,7 @@ class DeferRegressionTest(TestCase):
self.assertIn("Item_Deferred_name", klasses_with_deferred) self.assertIn("Item_Deferred_name", klasses_with_deferred)
self.assertTrue(any( self.assertTrue(any(
k._deferred for k in app_cache.get_models( k._deferred for k in app_cache.get_models(
app_cache.get_app("defer_regress"), include_deferred=True)) app_cache.get_app_config("defer_regress").models_module, include_deferred=True))
) )
@override_settings(SESSION_SERIALIZER='django.contrib.sessions.serializers.PickleSerializer') @override_settings(SESSION_SERIALIZER='django.contrib.sessions.serializers.PickleSerializer')

View File

@ -1,5 +1,4 @@
from django.apps import app_cache from django.apps import app_cache
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase from django.test import TestCase
from django.test.utils import override_settings from django.test.utils import override_settings
from django.utils import six from django.utils import six
@ -31,6 +30,6 @@ class NoModelTests(TestCase):
""" """
@override_settings(INSTALLED_APPS=("empty.no_models",)) @override_settings(INSTALLED_APPS=("empty.no_models",))
def test_no_models(self): def test_no_models(self):
with six.assertRaisesRegex(self, ImproperlyConfigured, with six.assertRaisesRegex(self, LookupError,
"No app with label 'no_models'."): "No app with label 'no_models'."):
app_cache.get_app('no_models') app_cache.get_app_config('no_models')

View File

@ -20,7 +20,7 @@ class SuiteOverrideTest(IgnoreAllDeprecationWarningsMixin, unittest.TestCase):
""" """
from django.test.simple import build_suite from django.test.simple import build_suite
app = app_cache.get_app("test_suite_override") app = app_cache.get_app_config("test_suite_override").models_module
suite = build_suite(app) suite = build_suite(app)
self.assertEqual(suite.countTestCases(), 1) self.assertEqual(suite.countTestCases(), 1)