1
0
mirror of https://github.com/django/django.git synced 2025-10-24 06:06:09 +00:00

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
This commit is contained in:
Jacob Kaplan-Moss
2009-03-18 16:55:59 +00:00
parent ee2f04d79e
commit c485e236bd
32 changed files with 128 additions and 71 deletions

View File

@@ -19,6 +19,7 @@ from cgi import parse_qsl
from django.conf import settings
from django.core import signals
from django.core.cache.backends.base import InvalidCacheBackendError
from django.utils import importlib
# Name for use in settings file --> name of module in "backends" directory.
# Any backend scheme that is not in this dictionary is treated as a Python
@@ -58,9 +59,10 @@ def parse_backend_uri(backend_uri):
def get_cache(backend_uri):
scheme, host, params = parse_backend_uri(backend_uri)
if scheme in BACKENDS:
module = __import__('django.core.cache.backends.%s' % BACKENDS[scheme], {}, {}, [''])
name = 'django.core.cache.backends.%s' % BACKENDS[scheme]
else:
module = __import__(scheme, {}, {}, [''])
name = scheme
module = importlib.import_module(name)
return getattr(module, 'CacheClass')(host, params)
cache = get_cache(settings.CACHE_BACKEND)

View File

@@ -8,6 +8,7 @@ from django.core.files import locks, File
from django.core.files.move import file_move_safe
from django.utils.encoding import force_unicode
from django.utils.functional import LazyObject
from django.utils.importlib import import_module
from django.utils.text import get_valid_filename
from django.utils._os import safe_join
@@ -230,7 +231,7 @@ def get_storage_class(import_path=None):
raise ImproperlyConfigured("%s isn't a storage module." % import_path)
module, classname = import_path[:dot], import_path[dot+1:]
try:
mod = __import__(module, {}, {}, [''])
mod = import_module(module)
except ImportError, e:
raise ImproperlyConfigured('Error importing storage module %s: "%s"' % (module, e))
try:

View File

@@ -10,6 +10,7 @@ except ImportError:
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.files.uploadedfile import TemporaryUploadedFile, InMemoryUploadedFile
from django.utils import importlib
__all__ = ['UploadFileException','StopUpload', 'SkipFile', 'FileUploadHandler',
'TemporaryFileUploadHandler', 'MemoryFileUploadHandler',
@@ -201,7 +202,7 @@ def load_handler(path, *args, **kwargs):
i = path.rfind('.')
module, attr = path[:i], path[i+1:]
try:
mod = __import__(module, {}, {}, [attr])
mod = importlib.import_module(module)
except ImportError, e:
raise ImproperlyConfigured('Error importing upload handler module %s: "%s"' % (module, e))
except ValueError, e:

View File

@@ -3,6 +3,7 @@ import sys
from django import http
from django.core import signals
from django.utils.encoding import force_unicode
from django.utils.importlib import import_module
class BaseHandler(object):
# Changes that are always applied to a response (in this order).
@@ -36,7 +37,7 @@ class BaseHandler(object):
raise exceptions.ImproperlyConfigured, '%s isn\'t a middleware module' % middleware_path
mw_module, mw_classname = middleware_path[:dot], middleware_path[dot+1:]
try:
mod = __import__(mw_module, {}, {}, [''])
mod = import_module(mw_module)
except ImportError, e:
raise exceptions.ImproperlyConfigured, 'Error importing middleware %s: "%s"' % (mw_module, e)
try:

View File

@@ -5,6 +5,7 @@ import imp
import django
from django.core.management.base import BaseCommand, CommandError, handle_default_options
from django.utils.importlib import import_module
# For backwards compatibility: get_version() used to be in this module.
get_version = django.get_version
@@ -63,8 +64,8 @@ def load_command_class(app_name, name):
class instance. All errors raised by the import process
(ImportError, AttributeError) are allowed to propagate.
"""
return getattr(__import__('%s.management.commands.%s' % (app_name, name),
{}, {}, ['Command']), 'Command')()
module = import_module('%s.management.commands.%s' % (app_name, name))
return module.Command()
def get_commands():
"""
@@ -104,12 +105,9 @@ def get_commands():
# Find the project directory
try:
from django.conf import settings
project_directory = setup_environ(
__import__(
settings.SETTINGS_MODULE, {}, {},
(settings.SETTINGS_MODULE.split(".")[-1],)
), settings.SETTINGS_MODULE
)
module = import_module(settings.SETTINGS_MODULE.split('.', 1)[0])
project_directory = setup_environ(module,
settings.SETTINGS_MODULE)
except (AttributeError, EnvironmentError, ImportError):
project_directory = None
@@ -328,7 +326,7 @@ def setup_environ(settings_mod, original_settings_path=None):
# Import the project module. We add the parent directory to PYTHONPATH to
# avoid some of the path errors new users can have.
sys.path.append(os.path.join(project_directory, os.pardir))
project_module = __import__(project_name, {}, {}, [''])
project_module = import_module(project_name)
sys.path.pop()
return project_directory

View File

@@ -1,5 +1,6 @@
from django.core.management.base import NoArgsCommand, CommandError
from django.core.management.color import no_style
from django.utils.importlib import import_module
from optparse import make_option
class Command(NoArgsCommand):
@@ -23,7 +24,7 @@ class Command(NoArgsCommand):
# dispatcher events.
for app_name in settings.INSTALLED_APPS:
try:
__import__(app_name + '.management', {}, {}, [''])
import_module('.management', app_name)
except ImportError:
pass

View File

@@ -1,6 +1,7 @@
import os
from django.core.management.base import copy_helper, CommandError, LabelCommand
from django.utils.importlib import import_module
class Command(LabelCommand):
help = "Creates a Django app directory structure for the given app name in the current directory."
@@ -26,7 +27,7 @@ class Command(LabelCommand):
# Check that the app_name cannot be imported.
try:
__import__(app_name)
import_module(app_name)
except ImportError:
pass
else:

View File

@@ -1,4 +1,5 @@
from django.core.management.base import copy_helper, CommandError, LabelCommand
from django.utils.importlib import import_module
import os
import re
from random import choice
@@ -20,7 +21,7 @@ class Command(LabelCommand):
# Check that the project_name cannot be imported.
try:
__import__(project_name)
import_module(project_name)
except ImportError:
pass
else:

View File

@@ -1,5 +1,6 @@
from django.core.management.base import NoArgsCommand
from django.core.management.color import no_style
from django.utils.importlib import import_module
from optparse import make_option
import sys
@@ -30,7 +31,7 @@ class Command(NoArgsCommand):
# dispatcher events.
for app_name in settings.INSTALLED_APPS:
try:
__import__(app_name + '.management', {}, {}, [''])
import_module('.management', app_name)
except ImportError, exc:
# This is slightly hackish. We want to ignore ImportErrors
# if the "management" module itself is missing -- but we don't

View File

@@ -17,6 +17,7 @@ To add your own serializers, use the SERIALIZATION_MODULES setting::
"""
from django.conf import settings
from django.utils import importlib
# Built-in serializers
BUILTIN_SERIALIZERS = {
@@ -47,7 +48,7 @@ def register_serializer(format, serializer_module, serializers=None):
directly into the global register of serializers. Adding serializers
directly is not a thread-safe operation.
"""
module = __import__(serializer_module, {}, {}, [''])
module = importlib.import_module(serializer_module)
if serializers is None:
_serializers[format] = module
else:

View File

@@ -12,6 +12,7 @@ Run with the extra option "help" for a list of additional options you can
pass to this server.
"""
from django.utils import importlib
import sys, os
__version__ = "0.1"
@@ -113,7 +114,7 @@ def runfastcgi(argset=[], **kwargs):
'maxSpare': int(options["maxspare"]),
'minSpare': int(options["minspare"]),
'maxChildren': int(options["maxchildren"]),
'maxRequests': int(options["maxrequests"]),
'maxRequests': int(options["maxrequests"]),
}
flup_module += '_fork'
elif options['method'] in ('thread', 'threaded'):
@@ -128,7 +129,8 @@ def runfastcgi(argset=[], **kwargs):
wsgi_opts['debug'] = False # Turn off flup tracebacks
try:
WSGIServer = getattr(__import__('flup.' + flup_module, '', '', flup_module), 'WSGIServer')
module = importlib_import_module('.%s' % flup_module, 'flup')
WSGIServer = module.WSGIServer
except:
print "Can't import flup." + flup_module
return False

View File

@@ -14,6 +14,7 @@ from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist
from django.utils.datastructures import MultiValueDict
from django.utils.encoding import iri_to_uri, force_unicode, smart_str
from django.utils.functional import memoize
from django.utils.importlib import import_module
from django.utils.regex_helper import normalize
from django.utils.thread_support import currentThread
@@ -54,7 +55,7 @@ def get_callable(lookup_view, can_fail=False):
lookup_view = lookup_view.encode('ascii')
mod_name, func_name = get_mod_func(lookup_view)
if func_name != '':
lookup_view = getattr(__import__(mod_name, {}, {}, ['']), func_name)
lookup_view = getattr(import_module(mod_name), func_name)
if not callable(lookup_view):
raise AttributeError("'%s.%s' is not a callable." % (mod_name, func_name))
except (ImportError, AttributeError):
@@ -199,7 +200,7 @@ class RegexURLResolver(object):
try:
return self._urlconf_module
except AttributeError:
self._urlconf_module = __import__(self.urlconf_name, {}, {}, [''])
self._urlconf_module = import_module(self.urlconf_name)
return self._urlconf_module
urlconf_module = property(_get_urlconf_module)
@@ -217,7 +218,7 @@ class RegexURLResolver(object):
callback = getattr(self.urlconf_module, 'handler%s' % view_type)
mod_name, func_name = get_mod_func(callback)
try:
return getattr(__import__(mod_name, {}, {}, ['']), func_name), {}
return getattr(import_module(mod_name), func_name), {}
except (ImportError, AttributeError), e:
raise ViewDoesNotExist, "Tried %s. Error was: %s" % (callback, str(e))