Fixed #2968 -- Changed arguments to __import__ to use empty dictionary instead of empty string, for stricter compliance with Python library reference. Thanks for the patch, Yasushi Masuda

git-svn-id: http://code.djangoproject.com/svn/django/trunk@3951 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Adrian Holovaty 2006-10-30 20:50:27 +00:00
parent 6d1335c058
commit 41d11a685f
17 changed files with 31 additions and 31 deletions

View File

@ -77,7 +77,7 @@ class Settings(object):
self.SETTINGS_MODULE = settings_module self.SETTINGS_MODULE = settings_module
try: try:
mod = __import__(self.SETTINGS_MODULE, '', '', ['']) mod = __import__(self.SETTINGS_MODULE, {}, {}, [''])
except ImportError, e: except ImportError, e:
raise EnvironmentError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e) raise EnvironmentError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
@ -97,7 +97,7 @@ class Settings(object):
new_installed_apps = [] new_installed_apps = []
for app in self.INSTALLED_APPS: for app in self.INSTALLED_APPS:
if app.endswith('.*'): if app.endswith('.*'):
appdir = os.path.dirname(__import__(app[:-2], '', '', ['']).__file__) appdir = os.path.dirname(__import__(app[:-2], {}, {}, ['']).__file__)
for d in os.listdir(appdir): for d in os.listdir(appdir):
if d.isalpha() and os.path.isdir(os.path.join(appdir, d)): if d.isalpha() and os.path.isdir(os.path.join(appdir, d)):
new_installed_apps.append('%s.%s' % (app[:-2], d)) new_installed_apps.append('%s.%s' % (app[:-2], d))

View File

@ -98,13 +98,13 @@ def view_index(request):
return missing_docutils_page(request) return missing_docutils_page(request)
if settings.ADMIN_FOR: if settings.ADMIN_FOR:
settings_modules = [__import__(m, '', '', ['']) for m in settings.ADMIN_FOR] settings_modules = [__import__(m, {}, {}, ['']) for m in settings.ADMIN_FOR]
else: else:
settings_modules = [settings] settings_modules = [settings]
views = [] views = []
for settings_mod in settings_modules: for settings_mod in settings_modules:
urlconf = __import__(settings_mod.ROOT_URLCONF, '', '', ['']) urlconf = __import__(settings_mod.ROOT_URLCONF, {}, {}, [''])
view_functions = extract_views_from_urlpatterns(urlconf.urlpatterns) view_functions = extract_views_from_urlpatterns(urlconf.urlpatterns)
if Site._meta.installed: if Site._meta.installed:
site_obj = Site.objects.get(pk=settings_mod.SITE_ID) site_obj = Site.objects.get(pk=settings_mod.SITE_ID)
@ -127,7 +127,7 @@ def view_detail(request, view):
mod, func = urlresolvers.get_mod_func(view) mod, func = urlresolvers.get_mod_func(view)
try: try:
view_func = getattr(__import__(mod, '', '', ['']), func) view_func = getattr(__import__(mod, {}, {}, ['']), func)
except (ImportError, AttributeError): except (ImportError, AttributeError):
raise Http404 raise Http404
title, body, metadata = utils.parse_docstring(view_func.__doc__) title, body, metadata = utils.parse_docstring(view_func.__doc__)
@ -235,7 +235,7 @@ model_detail = staff_member_required(model_detail)
def template_detail(request, template): def template_detail(request, template):
templates = [] templates = []
for site_settings_module in settings.ADMIN_FOR: for site_settings_module in settings.ADMIN_FOR:
settings_mod = __import__(site_settings_module, '', '', ['']) settings_mod = __import__(site_settings_module, {}, {}, [''])
if Site._meta.installed: if Site._meta.installed:
site_obj = Site.objects.get(pk=settings_mod.SITE_ID) site_obj = Site.objects.get(pk=settings_mod.SITE_ID)
else: else:

View File

@ -14,7 +14,7 @@ def template_validator(request):
# get a dict of {site_id : settings_module} for the validator # get a dict of {site_id : settings_module} for the validator
settings_modules = {} settings_modules = {}
for mod in settings.ADMIN_FOR: for mod in settings.ADMIN_FOR:
settings_module = __import__(mod, '', '', ['']) settings_module = __import__(mod, {}, {}, [''])
settings_modules[settings_module.SITE_ID] = settings_module settings_modules[settings_module.SITE_ID] = settings_module
manipulator = TemplateValidator(settings_modules) manipulator = TemplateValidator(settings_modules)
new_data, errors = {}, {} new_data, errors = {}, {}

View File

@ -9,7 +9,7 @@ def load_backend(path):
i = path.rfind('.') i = path.rfind('.')
module, attr = path[:i], path[i+1:] module, attr = path[:i], path[i+1:]
try: try:
mod = __import__(module, '', '', [attr]) mod = __import__(module, {}, {}, [attr])
except ImportError, e: except ImportError, e:
raise ImproperlyConfigured, 'Error importing authentication backend %s: "%s"' % (module, e) raise ImproperlyConfigured, 'Error importing authentication backend %s: "%s"' % (module, e)
try: try:

View File

@ -48,7 +48,7 @@ def get_cache(backend_uri):
if host.endswith('/'): if host.endswith('/'):
host = host[:-1] host = host[:-1]
cache_class = getattr(__import__('django.core.cache.backends.%s' % BACKENDS[scheme], '', '', ['']), 'CacheClass') cache_class = getattr(__import__('django.core.cache.backends.%s' % BACKENDS[scheme], {}, {}, ['']), 'CacheClass')
return cache_class(host, params) return cache_class(host, params)
cache = get_cache(settings.CACHE_BACKEND) cache = get_cache(settings.CACHE_BACKEND)

View File

@ -26,7 +26,7 @@ class BaseHandler(object):
raise exceptions.ImproperlyConfigured, '%s isn\'t a middleware module' % middleware_path raise exceptions.ImproperlyConfigured, '%s isn\'t a middleware module' % middleware_path
mw_module, mw_classname = middleware_path[:dot], middleware_path[dot+1:] mw_module, mw_classname = middleware_path[:dot], middleware_path[dot+1:]
try: try:
mod = __import__(mw_module, '', '', ['']) mod = __import__(mw_module, {}, {}, [''])
except ImportError, e: except ImportError, e:
raise exceptions.ImproperlyConfigured, 'Error importing middleware %s: "%s"' % (mw_module, e) raise exceptions.ImproperlyConfigured, 'Error importing middleware %s: "%s"' % (mw_module, e)
try: try:

View File

@ -446,7 +446,7 @@ def syncdb(verbosity=1, interactive=True):
# dispatcher events. # dispatcher events.
for app_name in settings.INSTALLED_APPS: for app_name in settings.INSTALLED_APPS:
try: try:
__import__(app_name + '.management', '', '', ['']) __import__(app_name + '.management', {}, {}, [''])
except ImportError: except ImportError:
pass pass
@ -1230,7 +1230,7 @@ def test(app_labels, verbosity=1):
test_module_name = '.'.join(test_path[:-1]) test_module_name = '.'.join(test_path[:-1])
else: else:
test_module_name = '.' test_module_name = '.'
test_module = __import__(test_module_name, [],[],test_path[-1]) test_module = __import__(test_module_name, {}, {}, test_path[-1])
test_runner = getattr(test_module, test_path[-1]) test_runner = getattr(test_module, test_path[-1])
test_runner(app_list, verbosity) test_runner(app_list, verbosity)
@ -1419,7 +1419,7 @@ def setup_environ(settings_mod):
project_directory = os.path.dirname(settings_mod.__file__) project_directory = os.path.dirname(settings_mod.__file__)
project_name = os.path.basename(project_directory) project_name = os.path.basename(project_directory)
sys.path.append(os.path.join(project_directory, '..')) sys.path.append(os.path.join(project_directory, '..'))
project_module = __import__(project_name, '', '', ['']) project_module = __import__(project_name, {}, {}, [''])
sys.path.pop() sys.path.pop()
# Set DJANGO_SETTINGS_MODULE appropriately. # Set DJANGO_SETTINGS_MODULE appropriately.

View File

@ -29,7 +29,7 @@ _serializers = {}
def register_serializer(format, serializer_module): def register_serializer(format, serializer_module):
"""Register a new serializer by passing in a module name.""" """Register a new serializer by passing in a module name."""
module = __import__(serializer_module, '', '', ['']) module = __import__(serializer_module, {}, {}, [''])
_serializers[format] = module _serializers[format] = module
def unregister_serializer(format): def unregister_serializer(format):

View File

@ -119,7 +119,7 @@ class RegexURLPattern(object):
return self._callback return self._callback
mod_name, func_name = get_mod_func(self._callback_str) mod_name, func_name = get_mod_func(self._callback_str)
try: try:
self._callback = getattr(__import__(mod_name, '', '', ['']), func_name) self._callback = getattr(__import__(mod_name, {}, {}, ['']), func_name)
except ImportError, e: except ImportError, e:
raise ViewDoesNotExist, "Could not import %s. Error was: %s" % (mod_name, str(e)) raise ViewDoesNotExist, "Could not import %s. Error was: %s" % (mod_name, str(e))
except AttributeError, e: except AttributeError, e:
@ -130,7 +130,7 @@ class RegexURLPattern(object):
def reverse(self, viewname, *args, **kwargs): def reverse(self, viewname, *args, **kwargs):
mod_name, func_name = get_mod_func(viewname) mod_name, func_name = get_mod_func(viewname)
try: try:
lookup_view = getattr(__import__(mod_name, '', '', ['']), func_name) lookup_view = getattr(__import__(mod_name, {}, {}, ['']), func_name)
except (ImportError, AttributeError): except (ImportError, AttributeError):
raise NoReverseMatch raise NoReverseMatch
if lookup_view != self.callback: if lookup_view != self.callback:
@ -171,7 +171,7 @@ class RegexURLResolver(object):
return self._urlconf_module return self._urlconf_module
except AttributeError: except AttributeError:
try: try:
self._urlconf_module = __import__(self.urlconf_name, '', '', ['']) self._urlconf_module = __import__(self.urlconf_name, {}, {}, [''])
except ValueError, e: except ValueError, e:
# Invalid urlconf_name, such as "foo.bar." (note trailing period) # Invalid urlconf_name, such as "foo.bar." (note trailing period)
raise ImproperlyConfigured, "Error while importing URLconf %r: %s" % (self.urlconf_name, e) raise ImproperlyConfigured, "Error while importing URLconf %r: %s" % (self.urlconf_name, e)
@ -186,7 +186,7 @@ class RegexURLResolver(object):
callback = getattr(self.urlconf_module, 'handler%s' % view_type) callback = getattr(self.urlconf_module, 'handler%s' % view_type)
mod_name, func_name = get_mod_func(callback) mod_name, func_name = get_mod_func(callback)
try: try:
return getattr(__import__(mod_name, '', '', ['']), func_name), {} return getattr(__import__(mod_name, {}, {}, ['']), func_name), {}
except (ImportError, AttributeError), e: except (ImportError, AttributeError), e:
raise ViewDoesNotExist, "Tried %s. Error was: %s" % (callback, str(e)) raise ViewDoesNotExist, "Tried %s. Error was: %s" % (callback, str(e))
@ -200,7 +200,7 @@ class RegexURLResolver(object):
if not callable(lookup_view): if not callable(lookup_view):
mod_name, func_name = get_mod_func(lookup_view) mod_name, func_name = get_mod_func(lookup_view)
try: try:
lookup_view = getattr(__import__(mod_name, '', '', ['']), func_name) lookup_view = getattr(__import__(mod_name, {}, {}, ['']), func_name)
except (ImportError, AttributeError): except (ImportError, AttributeError):
raise NoReverseMatch raise NoReverseMatch
for pattern in self.urlconf_module.urlpatterns: for pattern in self.urlconf_module.urlpatterns:

View File

@ -8,7 +8,7 @@ if not settings.DATABASE_ENGINE:
settings.DATABASE_ENGINE = 'dummy' settings.DATABASE_ENGINE = 'dummy'
try: try:
backend = __import__('django.db.backends.%s.base' % settings.DATABASE_ENGINE, '', '', ['']) backend = __import__('django.db.backends.%s.base' % settings.DATABASE_ENGINE, {}, {}, [''])
except ImportError, e: except ImportError, e:
# The database backend wasn't found. Display a helpful error message # The database backend wasn't found. Display a helpful error message
# listing all possible database backends. # listing all possible database backends.
@ -23,9 +23,9 @@ except ImportError, e:
else: else:
raise # If there's some other error, this must be an error in Django itself. raise # If there's some other error, this must be an error in Django itself.
get_introspection_module = lambda: __import__('django.db.backends.%s.introspection' % settings.DATABASE_ENGINE, '', '', ['']) get_introspection_module = lambda: __import__('django.db.backends.%s.introspection' % settings.DATABASE_ENGINE, {}, {}, [''])
get_creation_module = lambda: __import__('django.db.backends.%s.creation' % settings.DATABASE_ENGINE, '', '', ['']) get_creation_module = lambda: __import__('django.db.backends.%s.creation' % settings.DATABASE_ENGINE, {}, {}, [''])
runshell = lambda: __import__('django.db.backends.%s.client' % settings.DATABASE_ENGINE, '', '', ['']).runshell() runshell = lambda: __import__('django.db.backends.%s.client' % settings.DATABASE_ENGINE, {}, {}, ['']).runshell()
connection = backend.DatabaseWrapper() connection = backend.DatabaseWrapper()
DatabaseError = backend.DatabaseError DatabaseError = backend.DatabaseError

View File

@ -48,7 +48,7 @@ def get_app(app_label, emptyOK=False):
def load_app(app_name): def load_app(app_name):
"Loads the app with the provided fully qualified name, and returns the model module." "Loads the app with the provided fully qualified name, and returns the model module."
global _app_list global _app_list
mod = __import__(app_name, '', '', ['models']) mod = __import__(app_name, {}, {}, ['models'])
if not hasattr(mod, 'models'): if not hasattr(mod, 'models'):
return None return None
if mod.models not in _app_list: if mod.models not in _app_list:

View File

@ -883,7 +883,7 @@ def get_library(module_name):
lib = libraries.get(module_name, None) lib = libraries.get(module_name, None)
if not lib: if not lib:
try: try:
mod = __import__(module_name, '', '', ['']) mod = __import__(module_name, {}, {}, [''])
except ImportError, e: except ImportError, e:
raise InvalidTemplateLibrary, "Could not load template library from %s, %s" % (module_name, e) raise InvalidTemplateLibrary, "Could not load template library from %s, %s" % (module_name, e)
try: try:

View File

@ -69,7 +69,7 @@ def get_standard_processors():
i = path.rfind('.') i = path.rfind('.')
module, attr = path[:i], path[i+1:] module, attr = path[:i], path[i+1:]
try: try:
mod = __import__(module, '', '', [attr]) mod = __import__(module, {}, {}, [attr])
except ImportError, e: except ImportError, e:
raise ImproperlyConfigured, 'Error importing request processor module %s: "%s"' % (module, e) raise ImproperlyConfigured, 'Error importing request processor module %s: "%s"' % (module, e)
try: try:

View File

@ -15,9 +15,9 @@ for app in settings.INSTALLED_APPS:
m, a = app[:i], app[i+1:] m, a = app[:i], app[i+1:]
try: try:
if a is None: if a is None:
mod = __import__(m, '', '', []) mod = __import__(m, {}, {}, [])
else: else:
mod = getattr(__import__(m, '', '', [a]), a) mod = getattr(__import__(m, {}, {}, [a]), a)
except ImportError, e: except ImportError, e:
raise ImproperlyConfigured, 'ImportError %s: %s' % (app, e.args[0]) raise ImproperlyConfigured, 'ImportError %s: %s' % (app, e.args[0])
template_dir = os.path.join(os.path.dirname(mod.__file__), 'templates') template_dir = os.path.join(os.path.dirname(mod.__file__), 'templates')

View File

@ -2,6 +2,6 @@ from django.conf import settings
for a in settings.INSTALLED_APPS: for a in settings.INSTALLED_APPS:
try: try:
__path__.extend(__import__(a + '.templatetags', '', '', ['']).__path__) __path__.extend(__import__(a + '.templatetags', {}, {}, ['']).__path__)
except ImportError: except ImportError:
pass pass

View File

@ -28,7 +28,7 @@ def build_suite(app_module):
# models module # models module
try: try:
app_path = app_module.__name__.split('.')[:-1] app_path = app_module.__name__.split('.')[:-1]
test_module = __import__('.'.join(app_path + [TEST_MODULE]), [], [], TEST_MODULE) test_module = __import__('.'.join(app_path + [TEST_MODULE]), {}, {}, TEST_MODULE)
suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(test_module)) suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(test_module))
try: try:

View File

@ -75,7 +75,7 @@ def technical_500_response(request, exc_type, exc_value, tb):
loader_debug_info = [] loader_debug_info = []
for loader in template_source_loaders: for loader in template_source_loaders:
try: try:
source_list_func = getattr(__import__(loader.__module__, '', '', ['get_template_sources']), 'get_template_sources') source_list_func = getattr(__import__(loader.__module__, {}, {}, ['get_template_sources']), 'get_template_sources')
# NOTE: This assumes exc_value is the name of the template that # NOTE: This assumes exc_value is the name of the template that
# the loader attempted to load. # the loader attempted to load.
template_list = [{'name': t, 'exists': os.path.exists(t)} \ template_list = [{'name': t, 'exists': os.path.exists(t)} \