Skip to content

Commit c485e23

Browse files
committed
Fixed #8193: all dynamic imports in Django are now done correctly. I know this because Brett Cannon borrowed the time machine and brought Python 2.7's 'importlib back for inclusion in Django. Thanks for the patch-from-the-future, Brett!
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10088 bcc190cf-cafb-0310-a4f2-bffc1f526a37
1 parent ee2f04d commit c485e23

File tree

32 files changed

+128
-71
lines changed

32 files changed

+128
-71
lines changed

AUTHORS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ answer newbie questions, and generally made Django that much better:
7575
Chris Cahoon <[email protected]>
7676
Juan Manuel Caicedo <[email protected]>
7777
Trevor Caira <[email protected]>
78+
Brett Cannon <[email protected]>
7879
Ricardo Javier Cárdenes Medina <[email protected]>
7980
Jeremy Carbaugh <[email protected]>
8081

django/conf/__init__.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
from django.conf import global_settings
1414
from django.utils.functional import LazyObject
15+
from django.utils import importlib
1516

1617
ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE"
1718

@@ -69,7 +70,7 @@ def __init__(self, settings_module):
6970
self.SETTINGS_MODULE = settings_module
7071

7172
try:
72-
mod = __import__(self.SETTINGS_MODULE, {}, {}, [''])
73+
mod = importlib.import_module(self.SETTINGS_MODULE)
7374
except ImportError, e:
7475
raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
7576

@@ -89,7 +90,8 @@ def __init__(self, settings_module):
8990
new_installed_apps = []
9091
for app in self.INSTALLED_APPS:
9192
if app.endswith('.*'):
92-
appdir = os.path.dirname(__import__(app[:-2], {}, {}, ['']).__file__)
93+
app_mod = importlib.import_module(app[:-2])
94+
appdir = os.path.dirname(app_mod.__file__)
9395
app_subdirs = os.listdir(appdir)
9496
app_subdirs.sort()
9597
name_pattern = re.compile(r'[a-zA-Z]\w*')

django/contrib/admin/__init__.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL
22
from django.contrib.admin.options import StackedInline, TabularInline
33
from django.contrib.admin.sites import AdminSite, site
4+
from django.utils.importlib import import_module
45

56
# A flag to tell us if autodiscover is running. autodiscover will set this to
67
# True while running, and False when it finishes.
@@ -36,7 +37,7 @@ def autodiscover():
3637
# fails silently -- apps that do weird things with __path__ might
3738
# need to roll their own admin registration.
3839
try:
39-
app_path = __import__(app, {}, {}, [app.split('.')[-1]]).__path__
40+
app_path = import_module(app).__path__
4041
except AttributeError:
4142
continue
4243

@@ -51,6 +52,6 @@ def autodiscover():
5152

5253
# Step 3: import the app's admin file. If this has errors we want them
5354
# to bubble up.
54-
__import__("%s.admin" % app)
55+
import_module("%s.admin" % app)
5556
# autodiscover was successful, reset loading flag.
5657
LOADING = False

django/contrib/admin/views/template.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from django.shortcuts import render_to_response
55
from django.contrib.sites.models import Site
66
from django.conf import settings
7+
from django.utils.importlib import import_module
78
from django.utils.translation import ugettext_lazy as _
89

910

@@ -15,7 +16,7 @@ def template_validator(request):
1516
# get a dict of {site_id : settings_module} for the validator
1617
settings_modules = {}
1718
for mod in settings.ADMIN_FOR:
18-
settings_module = __import__(mod, {}, {}, [''])
19+
settings_module = import_module(mod)
1920
settings_modules[settings_module.SITE_ID] = settings_module
2021
site_list = Site.objects.in_bulk(settings_modules.keys()).values()
2122
if request.POST:

django/contrib/admindocs/views.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from django.core import urlresolvers
1010
from django.contrib.admindocs import utils
1111
from django.contrib.sites.models import Site
12+
from django.utils.importlib import import_module
1213
from django.utils.translation import ugettext as _
1314
from django.utils.safestring import mark_safe
1415
import inspect, os, re
@@ -114,13 +115,13 @@ def view_index(request):
114115
return missing_docutils_page(request)
115116

116117
if settings.ADMIN_FOR:
117-
settings_modules = [__import__(m, {}, {}, ['']) for m in settings.ADMIN_FOR]
118+
settings_modules = [import_module(m) for m in settings.ADMIN_FOR]
118119
else:
119120
settings_modules = [settings]
120121

121122
views = []
122123
for settings_mod in settings_modules:
123-
urlconf = __import__(settings_mod.ROOT_URLCONF, {}, {}, [''])
124+
urlconf = import_module(settings_mod.ROOT_URLCONF)
124125
view_functions = extract_views_from_urlpatterns(urlconf.urlpatterns)
125126
if Site._meta.installed:
126127
site_obj = Site.objects.get(pk=settings_mod.SITE_ID)
@@ -146,7 +147,7 @@ def view_detail(request, view):
146147

147148
mod, func = urlresolvers.get_mod_func(view)
148149
try:
149-
view_func = getattr(__import__(mod, {}, {}, ['']), func)
150+
view_func = getattr(import_module(mod), func)
150151
except (ImportError, AttributeError):
151152
raise Http404
152153
title, body, metadata = utils.parse_docstring(view_func.__doc__)
@@ -257,7 +258,7 @@ def model_detail(request, app_label, model_name):
257258
def template_detail(request, template):
258259
templates = []
259260
for site_settings_module in settings.ADMIN_FOR:
260-
settings_mod = __import__(site_settings_module, {}, {}, [''])
261+
settings_mod = import_module(site_settings_module)
261262
if Site._meta.installed:
262263
site_obj = Site.objects.get(pk=settings_mod.SITE_ID)
263264
else:

django/contrib/auth/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import datetime
22
from django.core.exceptions import ImproperlyConfigured
3+
from django.utils.importlib import import_module
34

45
SESSION_KEY = '_auth_user_id'
56
BACKEND_SESSION_KEY = '_auth_user_backend'
@@ -9,7 +10,7 @@ def load_backend(path):
910
i = path.rfind('.')
1011
module, attr = path[:i], path[i+1:]
1112
try:
12-
mod = __import__(module, {}, {}, [attr])
13+
mod = import_module(module)
1314
except ImportError, e:
1415
raise ImproperlyConfigured, 'Error importing authentication backend %s: "%s"' % (module, e)
1516
except ValueError, e:

django/contrib/comments/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from django.core.exceptions import ImproperlyConfigured
44
from django.contrib.comments.models import Comment
55
from django.contrib.comments.forms import CommentForm
6+
from django.utils.importlib import import_module
67

78
DEFAULT_COMMENTS_APP = 'django.contrib.comments'
89

@@ -18,7 +19,7 @@ def get_comment_app():
1819

1920
# Try to import the package
2021
try:
21-
package = __import__(comments_app, '', '', [''])
22+
package = import_module(comments_app)
2223
except ImportError:
2324
raise ImproperlyConfigured("The COMMENTS_APP setting refers to "\
2425
"a non-existing package.")

django/contrib/sessions/middleware.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@
33
from django.conf import settings
44
from django.utils.cache import patch_vary_headers
55
from django.utils.http import cookie_date
6+
from django.utils.importlib import import_module
67

78
class SessionMiddleware(object):
89
def process_request(self, request):
9-
engine = __import__(settings.SESSION_ENGINE, {}, {}, [''])
10+
engine = import_module(settings.SESSION_ENGINE)
1011
session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)
1112
request.session = engine.SessionStore(session_key)
1213

django/core/cache/__init__.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
from django.conf import settings
2020
from django.core import signals
2121
from django.core.cache.backends.base import InvalidCacheBackendError
22+
from django.utils import importlib
2223

2324
# Name for use in settings file --> name of module in "backends" directory.
2425
# Any backend scheme that is not in this dictionary is treated as a Python
@@ -58,9 +59,10 @@ def parse_backend_uri(backend_uri):
5859
def get_cache(backend_uri):
5960
scheme, host, params = parse_backend_uri(backend_uri)
6061
if scheme in BACKENDS:
61-
module = __import__('django.core.cache.backends.%s' % BACKENDS[scheme], {}, {}, [''])
62+
name = 'django.core.cache.backends.%s' % BACKENDS[scheme]
6263
else:
63-
module = __import__(scheme, {}, {}, [''])
64+
name = scheme
65+
module = importlib.import_module(name)
6466
return getattr(module, 'CacheClass')(host, params)
6567

6668
cache = get_cache(settings.CACHE_BACKEND)

django/core/files/storage.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from django.core.files.move import file_move_safe
99
from django.utils.encoding import force_unicode
1010
from django.utils.functional import LazyObject
11+
from django.utils.importlib import import_module
1112
from django.utils.text import get_valid_filename
1213
from django.utils._os import safe_join
1314

@@ -230,7 +231,7 @@ def get_storage_class(import_path=None):
230231
raise ImproperlyConfigured("%s isn't a storage module." % import_path)
231232
module, classname = import_path[:dot], import_path[dot+1:]
232233
try:
233-
mod = __import__(module, {}, {}, [''])
234+
mod = import_module(module)
234235
except ImportError, e:
235236
raise ImproperlyConfigured('Error importing storage module %s: "%s"' % (module, e))
236237
try:

0 commit comments

Comments
 (0)