Ticket #8193: importlib.diff

File importlib.diff, 34.0 KB (added by Brett Cannon, 16 years ago)

Add importlib to django.utils and move all import usage over to it.

  • django/test/client.py

     
    1919from django.utils.encoding import smart_str
    2020from django.utils.http import urlencode
    2121from django.utils.itercompat import is_iterable
     22from django.utils.importlib import import_module
    2223from django.db import transaction, close_connection
    2324
    2425BOUNDARY = 'BoUnDaRyStRiNg'
     
    175176        Obtains the current session variables.
    176177        """
    177178        if 'django.contrib.sessions' in settings.INSTALLED_APPS:
    178             engine = __import__(settings.SESSION_ENGINE, {}, {}, [''])
     179            engine = import_module(settings.SESSION_ENGINE)
    179180            cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None)
    180181            if cookie:
    181182                return engine.SessionStore(cookie.value)
     
    398399        user = authenticate(**credentials)
    399400        if user and user.is_active \
    400401                and 'django.contrib.sessions' in settings.INSTALLED_APPS:
    401             engine = __import__(settings.SESSION_ENGINE, {}, {}, [''])
     402            engine = import_module(settings.SESSION_ENGINE)
    402403
    403404            # Create a fake request to store login details.
    404405            request = HttpRequest()
     
    433434
    434435        Causes the authenticated user to be logged out.
    435436        """
    436         session = __import__(settings.SESSION_ENGINE, {}, {}, ['']).SessionStore()
     437        session = import_module(settings.SESSION_ENGINE).SessionStore()
    437438        session.delete(session_key=self.cookies[settings.SESSION_COOKIE_NAME].value)
    438439        self.cookies = SimpleCookie()
    439440
  • django/db/models/loading.py

     
    33from django.conf import settings
    44from django.core.exceptions import ImproperlyConfigured
    55from django.utils.datastructures import SortedDict
     6from django.utils.importlib import import_module
    67
    78import sys
    89import os
     
    6970        """
    7071        self.handled[app_name] = None
    7172        self.nesting_level += 1
    72         mod = __import__(app_name, {}, {}, ['models'])
    73         self.nesting_level -= 1
    74         if not hasattr(mod, 'models'):
     73        try:
     74            models = import_module('.models', app_name)
     75        except ImportError:
     76            self.nesting_level -= 1
    7577            if can_postpone:
    7678                # Either the app has no models, or the package is still being
    7779                # imported by Python and the model module isn't available yet.
     
    7981                # populate).
    8082                self.postponed.append(app_name)
    8183            return None
    82         if mod.models not in self.app_store:
    83             self.app_store[mod.models] = len(self.app_store)
    84         return mod.models
     84        self.nesting_level -= 1
     85        if models not in self.app_store:
     86            self.app_store[models] = len(self.app_store)
     87        return models
    8588
    8689    def app_cache_ready(self):
    8790        """
  • django/db/__init__.py

     
    33from django.core import signals
    44from django.core.exceptions import ImproperlyConfigured
    55from django.utils.functional import curry
     6from django.utils.importlib import import_module
    67
    78__all__ = ('backend', 'connection', 'DatabaseError', 'IntegrityError')
    89
     
    1314    # Most of the time, the database backend will be one of the official
    1415    # backends that ships with Django, so look there first.
    1516    _import_path = 'django.db.backends.'
    16     backend = __import__('%s%s.base' % (_import_path, settings.DATABASE_ENGINE), {}, {}, [''])
     17    backend = import_module('.base',
     18                            '%s%s' % (_import_path, settings.DATABASE_ENGINE))
    1719except ImportError, e:
    1820    # If the import failed, we might be looking for a database backend
    1921    # distributed external to Django. So we'll try that next.
    2022    try:
    2123        _import_path = ''
    22         backend = __import__('%s.base' % settings.DATABASE_ENGINE, {}, {}, [''])
     24        backend = import_module('.base', settings.DATABASE_ENGINE)
    2325    except ImportError, e_user:
    2426        # The database backend wasn't found. Display a helpful error message
    2527        # listing all possible (built-in) database backends.
  • django/conf/__init__.py

     
    1111
    1212from django.conf import global_settings
    1313from django.utils.functional import LazyObject
     14from django.utils import importlib
    1415
    1516ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE"
    1617
     
    6869        self.SETTINGS_MODULE = settings_module
    6970
    7071        try:
    71             mod = __import__(self.SETTINGS_MODULE, {}, {}, [''])
     72            mod = importlib.import_module(self.SETTINGS_MODULE)
    7273        except ImportError, e:
    7374            raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
    7475
     
    8889        new_installed_apps = []
    8990        for app in self.INSTALLED_APPS:
    9091            if app.endswith('.*'):
    91                 appdir = os.path.dirname(__import__(app[:-2], {}, {}, ['']).__file__)
     92                app_mod = importlib.import_module(app[:-2])
     93                appdir = os.path.dirname(app_mod.__file__)
    9294                app_subdirs = os.listdir(appdir)
    9395                app_subdirs.sort()
    9496                for d in app_subdirs:
  • django/core/servers/fastcgi.py

     
    1212pass to this server.
    1313"""
    1414
     15from django.utils import importlib
    1516import sys, os
    1617
    1718__version__ = "0.1"
     
    113114            'maxSpare': int(options["maxspare"]),
    114115            'minSpare': int(options["minspare"]),
    115116            'maxChildren': int(options["maxchildren"]),
    116             'maxRequests': int(options["maxrequests"]), 
     117            'maxRequests': int(options["maxrequests"]),
    117118        }
    118119        flup_module += '_fork'
    119120    elif options['method'] in ('thread', 'threaded'):
     
    128129    wsgi_opts['debug'] = False # Turn off flup tracebacks
    129130
    130131    try:
    131         WSGIServer = getattr(__import__('flup.' + flup_module, '', '', flup_module), 'WSGIServer')
     132        module = importlib_import_module('.%s' % flup_module, 'flup')
     133        WSGIServer = module.WSGIServer
    132134    except:
    133135        print "Can't import flup." + flup_module
    134136        return False
  • django/core/serializers/__init__.py

     
    1717"""
    1818
    1919from django.conf import settings
     20from django.utils import importlib
    2021
    2122# Built-in serializers
    2223BUILTIN_SERIALIZERS = {
     
    4748    directly into the global register of serializers. Adding serializers
    4849    directly is not a thread-safe operation.
    4950    """
    50     module = __import__(serializer_module, {}, {}, [''])
     51    module = importlib.import_module(serializer_module)
    5152    if serializers is None:
    5253        _serializers[format] = module
    5354    else:
  • django/core/urlresolvers.py

     
    1414from django.utils.datastructures import MultiValueDict
    1515from django.utils.encoding import iri_to_uri, force_unicode, smart_str
    1616from django.utils.functional import memoize
     17from django.utils.importlib import import_module
    1718from django.utils.regex_helper import normalize
    1819from django.utils.thread_support import currentThread
    1920
     
    5455            lookup_view = lookup_view.encode('ascii')
    5556            mod_name, func_name = get_mod_func(lookup_view)
    5657            if func_name != '':
    57                 lookup_view = getattr(__import__(mod_name, {}, {}, ['']), func_name)
     58                lookup_view = getattr(import_module(mod_name), func_name)
    5859                if not callable(lookup_view):
    5960                    raise AttributeError("'%s.%s' is not a callable." % (mod_name, func_name))
    6061        except (ImportError, AttributeError):
     
    197198        try:
    198199            return self._urlconf_module
    199200        except AttributeError:
    200             self._urlconf_module = __import__(self.urlconf_name, {}, {}, [''])
     201            self._urlconf_module = import_module(self.urlconf_name)
    201202            return self._urlconf_module
    202203    urlconf_module = property(_get_urlconf_module)
    203204
     
    215216        callback = getattr(self.urlconf_module, 'handler%s' % view_type)
    216217        mod_name, func_name = get_mod_func(callback)
    217218        try:
    218             return getattr(__import__(mod_name, {}, {}, ['']), func_name), {}
     219            return getattr(import_module(mod_name), func_name), {}
    219220        except (ImportError, AttributeError), e:
    220221            raise ViewDoesNotExist, "Tried %s. Error was: %s" % (callback, str(e))
    221222
  • django/core/handlers/base.py

     
    33from django import http
    44from django.core import signals
    55from django.utils.encoding import force_unicode
     6from django.utils.importlib import import_module
    67
    78class BaseHandler(object):
    89    # Changes that are always applied to a response (in this order).
     
    3536                raise exceptions.ImproperlyConfigured, '%s isn\'t a middleware module' % middleware_path
    3637            mw_module, mw_classname = middleware_path[:dot], middleware_path[dot+1:]
    3738            try:
    38                 mod = __import__(mw_module, {}, {}, [''])
     39                mod = import_module(mw_module)
    3940            except ImportError, e:
    4041                raise exceptions.ImproperlyConfigured, 'Error importing middleware %s: "%s"' % (mw_module, e)
    4142            try:
  • django/core/files/uploadhandler.py

     
    1010from django.conf import settings
    1111from django.core.exceptions import ImproperlyConfigured
    1212from django.core.files.uploadedfile import TemporaryUploadedFile, InMemoryUploadedFile
     13from django.utils import importlib
    1314
    1415__all__ = ['UploadFileException','StopUpload', 'SkipFile', 'FileUploadHandler',
    1516           'TemporaryFileUploadHandler', 'MemoryFileUploadHandler',
     
    201202    i = path.rfind('.')
    202203    module, attr = path[:i], path[i+1:]
    203204    try:
    204         mod = __import__(module, {}, {}, [attr])
     205        mod = importlib.import_module(module)
    205206    except ImportError, e:
    206207        raise ImproperlyConfigured('Error importing upload handler module %s: "%s"' % (module, e))
    207208    except ValueError, e:
  • django/core/files/storage.py

     
    88from django.core.files.move import file_move_safe
    99from django.utils.encoding import force_unicode
    1010from django.utils.functional import LazyObject
     11from django.utils.importlib import import_module
    1112from django.utils.text import get_valid_filename
    1213from django.utils._os import safe_join
    1314
     
    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:
  • django/core/cache/__init__.py

     
    1919from django.conf import settings
    2020from django.core import signals
    2121from django.core.cache.backends.base import InvalidCacheBackendError
     22from 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
     
    5859def 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
    6668cache = get_cache(settings.CACHE_BACKEND)
  • django/core/management/commands/startapp.py

     
    11import os
    22
    33from django.core.management.base import copy_helper, CommandError, LabelCommand
     4from django.utils.importlib import import_module
    45
    56class Command(LabelCommand):
    67    help = "Creates a Django app directory structure for the given app name in the current directory."
     
    2627
    2728        # Check that the app_name cannot be imported.
    2829        try:
    29             __import__(app_name)
     30            import_module(app_name)
    3031        except ImportError:
    3132            pass
    3233        else:
  • django/core/management/commands/flush.py

     
    11from django.core.management.base import NoArgsCommand, CommandError
    22from django.core.management.color import no_style
     3from django.utils.importlib import import_module
    34from optparse import make_option
    45
    56class Command(NoArgsCommand):
     
    2324        # dispatcher events.
    2425        for app_name in settings.INSTALLED_APPS:
    2526            try:
    26                 __import__(app_name + '.management', {}, {}, [''])
     27                import_module('.management', app_name)
    2728            except ImportError:
    2829                pass
    2930
  • django/core/management/commands/syncdb.py

     
    11from django.core.management.base import NoArgsCommand
    22from django.core.management.color import no_style
     3from django.utils.importlib import import_module
    34from optparse import make_option
    45import sys
    56
     
    3031        # dispatcher events.
    3132        for app_name in settings.INSTALLED_APPS:
    3233            try:
    33                 __import__(app_name + '.management', {}, {}, [''])
     34                import_module('.management', app_name)
    3435            except ImportError, exc:
    3536                # This is slightly hackish. We want to ignore ImportErrors
    3637                # if the "management" module itself is missing -- but we don't
  • django/core/management/commands/startproject.py

     
    11from django.core.management.base import copy_helper, CommandError, LabelCommand
     2from django.utils.importlib import import_module
    23import os
    34import re
    45from random import choice
     
    2021
    2122        # Check that the project_name cannot be imported.
    2223        try:
    23             __import__(project_name)
     24            import_module(project_name)
    2425        except ImportError:
    2526            pass
    2627        else:
  • django/core/management/__init__.py

     
    55
    66import django
    77from django.core.management.base import BaseCommand, CommandError, handle_default_options
     8from django.utils.importlib import import_module
    89
    910# For backwards compatibility: get_version() used to be in this module.
    1011get_version = django.get_version
     
    6364    class instance. All errors raised by the import process
    6465    (ImportError, AttributeError) are allowed to propagate.
    6566    """
    66     return getattr(__import__('%s.management.commands.%s' % (app_name, name),
    67                    {}, {}, ['Command']), 'Command')()
     67    module = import_module('%s.management.commands.%s' % (app_name, name))
     68    return module.Command()
    6869
    6970def get_commands():
    7071    """
     
    104105        # Find the project directory
    105106        try:
    106107            from django.conf import settings
    107             project_directory = setup_environ(
    108                 __import__(
    109                     settings.SETTINGS_MODULE, {}, {},
    110                     (settings.SETTINGS_MODULE.split(".")[-1],)
    111                 ), settings.SETTINGS_MODULE
    112             )
     108            module = import_module(settings.SETTINGS_MODULE.split('.', 1)[0])
     109            project_directory = setup_environ(module,
     110                                                settings.SETTINGS_MODULE)
    113111        except (AttributeError, EnvironmentError, ImportError):
    114112            project_directory = None
    115113
     
    328326    # Import the project module. We add the parent directory to PYTHONPATH to
    329327    # avoid some of the path errors new users can have.
    330328    sys.path.append(os.path.join(project_directory, os.pardir))
    331     project_module = __import__(project_name, {}, {}, [''])
     329    project_module = import_module(project_name)
    332330    sys.path.pop()
    333331
    334332    return project_directory
  • django/templatetags/__init__.py

     
    11from django.conf import settings
     2from django.utils import importlib
    23
    34for a in settings.INSTALLED_APPS:
    45    try:
    5         __path__.extend(__import__(a + '.templatetags', {}, {}, ['']).__path__)
     6        __path__.extend(importlib.import_module('.templatetags', a).__path__)
    67    except ImportError:
    78        pass
  • django/views/i18n.py

     
    11from django import http
     2from django.conf import settings
     3from django.utils import importlib
    24from django.utils.translation import check_for_language, activate, to_locale, get_language
    35from django.utils.text import javascript_quote
    4 from django.conf import settings
    56import os
    67import gettext as gettext_module
    78
     
    128129    paths = []
    129130    # first load all english languages files for defaults
    130131    for package in packages:
    131         p = __import__(package, {}, {}, [''])
     132        p = importlib.import_module(package)
    132133        path = os.path.join(os.path.dirname(p.__file__), 'locale')
    133134        paths.append(path)
    134135        try:
  • django/views/debug.py

     
    66from django.conf import settings
    77from django.template import Template, Context, TemplateDoesNotExist
    88from django.utils.html import escape
     9from django.utils.importlib import import_module
    910from django.http import HttpResponse, HttpResponseServerError, HttpResponseNotFound
    1011from django.utils.encoding import smart_unicode, smart_str
    1112
     
    6768            self.loader_debug_info = []
    6869            for loader in template_source_loaders:
    6970                try:
    70                     source_list_func = getattr(__import__(loader.__module__, {}, {}, ['get_template_sources']), 'get_template_sources')
     71                    module = import_module(loader.__module__)
     72                    source_list_func = module.get_template_sources
    7173                    # NOTE: This assumes exc_value is the name of the template that
    7274                    # the loader attempted to load.
    7375                    template_list = [{'name': t, 'exists': os.path.exists(t)} \
  • django/utils/importlib.py

     
     1# Taken from Python 2.7 with permission from/by the original author.
     2import sys
     3
     4def _resolve_name(name, package, level):
     5    """Return the absolute name of the module to be imported."""
     6    if not hasattr(package, 'rindex'):
     7        raise ValueError("'package' not set to a string")
     8    dot = len(package)
     9    for x in xrange(level, 1, -1):
     10        try:
     11            dot = package.rindex('.', 0, dot)
     12        except ValueError:
     13            raise ValueError("attempted relative import beyond top-level "
     14                              "package")
     15    return "%s.%s" % (package[:dot], name)
     16
     17
     18def import_module(name, package=None):
     19    """Import a module.
     20
     21    The 'package' argument is required when performing a relative import. It
     22    specifies the package to use as the anchor point from which to resolve the
     23    relative import to an absolute import.
     24
     25    """
     26    if name.startswith('.'):
     27        if not package:
     28            raise TypeError("relative imports require the 'package' argument")
     29        level = 0
     30        for character in name:
     31            if character != '.':
     32                break
     33            level += 1
     34        name = _resolve_name(name[level:], package, level)
     35    __import__(name)
     36    return sys.modules[name]
  • django/utils/translation/trans_real.py

     
    77import gettext as gettext_module
    88from cStringIO import StringIO
    99
     10from django.utils.importlib import import_module
    1011from django.utils.safestring import mark_safe, SafeData
    1112from django.utils.thread_support import currentThread
    1213
     
    125126
    126127    if settings.SETTINGS_MODULE is not None:
    127128        parts = settings.SETTINGS_MODULE.split('.')
    128         project = __import__(parts[0], {}, {}, [])
     129        project = import_module(parts[0])
    129130        projectpath = os.path.join(os.path.dirname(project.__file__), 'locale')
    130131    else:
    131132        projectpath = None
     
    176177            res = _merge(projectpath)
    177178
    178179        for appname in settings.INSTALLED_APPS:
    179             p = appname.rfind('.')
    180             if p >= 0:
    181                 app = getattr(__import__(appname[:p], {}, {}, [appname[p+1:]]), appname[p+1:])
    182             else:
    183                 app = __import__(appname, {}, {}, [])
    184 
     180            app = import_module(appname)
    185181            apppath = os.path.join(os.path.dirname(app.__file__), 'locale')
    186182
    187183            if os.path.isdir(apppath):
  • django/contrib/comments/__init__.py

     
    33from django.core.exceptions import ImproperlyConfigured
    44from django.contrib.comments.models import Comment
    55from django.contrib.comments.forms import CommentForm
     6from django.utils.importlib import import_module
    67
    78DEFAULT_COMMENTS_APP = 'django.contrib.comments'
    89
     
    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/admin/__init__.py

     
    11from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL
    22from django.contrib.admin.options import StackedInline, TabularInline
    33from django.contrib.admin.sites import AdminSite, site
     4from 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.
     
    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
     
    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

     
    44from django.shortcuts import render_to_response
    55from django.contrib.sites.models import Site
    66from django.conf import settings
     7from django.utils.importlib import import_module
    78from django.utils.translation import ugettext_lazy as _
    89
    910
     
    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

     
    99from django.core import urlresolvers
    1010from django.contrib.admindocs import utils
    1111from django.contrib.sites.models import Site
     12from django.utils.importlib import import_module
    1213from django.utils.translation import ugettext as _
    1314from django.utils.safestring import mark_safe
    1415import inspect, os, re
     
    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)
     
    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__)
     
    257258def 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

     
    11import datetime
    22from django.core.exceptions import ImproperlyConfigured
     3from django.utils.importlib import import_module
    34
    45SESSION_KEY = '_auth_user_id'
    56BACKEND_SESSION_KEY = '_auth_user_backend'
     
    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/sessions/middleware.py

     
    33from django.conf import settings
    44from django.utils.cache import patch_vary_headers
    55from django.utils.http import cookie_date
     6from django.utils.importlib import import_module
    67
    78class 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/template/__init__.py

     
    5252from inspect import getargspec
    5353from django.conf import settings
    5454from django.template.context import Context, RequestContext, ContextPopException
     55from django.utils.importlib import import_module
    5556from django.utils.itercompat import is_iterable
    5657from django.utils.functional import curry, Promise
    5758from django.utils.text import smart_split
     
    935936    lib = libraries.get(module_name, None)
    936937    if not lib:
    937938        try:
    938             mod = __import__(module_name, {}, {}, [''])
     939            mod = import_module(module_name)
    939940        except ImportError, e:
    940941            raise InvalidTemplateLibrary("Could not load template library from %s, %s" % (module_name, e))
    941942        try:
  • django/template/loaders/app_directories.py

     
    1010from django.core.exceptions import ImproperlyConfigured
    1111from django.template import TemplateDoesNotExist
    1212from django.utils._os import safe_join
     13from django.utils.importlib import import_module
    1314
    1415# At compile time, cache the directories to search.
    1516fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
    1617app_template_dirs = []
    1718for app in settings.INSTALLED_APPS:
    18     i = app.rfind('.')
    19     if i == -1:
    20         m, a = app, None
    21     else:
    22         m, a = app[:i], app[i+1:]
    2319    try:
    24         if a is None:
    25             mod = __import__(m, {}, {}, [])
    26         else:
    27             mod = getattr(__import__(m, {}, {}, [a]), a)
     20        mod = import_module(app)
    2821    except ImportError, e:
    2922        raise ImproperlyConfigured, 'ImportError %s: %s' % (app, e.args[0])
    3023    template_dir = os.path.join(os.path.dirname(mod.__file__), 'templates')
  • django/template/context.py

     
    11from django.conf import settings
    22from django.core.exceptions import ImproperlyConfigured
     3from django.utils.importlib import import_module
    34
    45_standard_context_processors = None
    56
     
    6263
    6364    def update(self, other_dict):
    6465        "Like dict.update(). Pushes an entire dictionary's keys and values onto the context."
    65         if not hasattr(other_dict, '__getitem__'): 
     66        if not hasattr(other_dict, '__getitem__'):
    6667            raise TypeError('other_dict must be a mapping (dictionary-like) object.')
    6768        self.dicts = [other_dict] + self.dicts
    6869        return other_dict
     
    7778            i = path.rfind('.')
    7879            module, attr = path[:i], path[i+1:]
    7980            try:
    80                 mod = __import__(module, {}, {}, [attr])
     81                mod = import_module(module)
    8182            except ImportError, e:
    8283                raise ImproperlyConfigured('Error importing request processor module %s: "%s"' % (module, e))
    8384            try:
  • django/template/loader.py

     
    2222
    2323from django.core.exceptions import ImproperlyConfigured
    2424from django.template import Origin, Template, Context, TemplateDoesNotExist, add_to_builtins
     25from django.utils.importlib import import_module
    2526from django.conf import settings
    2627
    2728template_source_loaders = None
     
    5152            i = path.rfind('.')
    5253            module, attr = path[:i], path[i+1:]
    5354            try:
    54                 mod = __import__(module, globals(), locals(), [attr])
     55                mod = import_module(module)
    5556            except ImportError, e:
    5657                raise ImproperlyConfigured, 'Error importing template source loader %s: "%s"' % (module, e)
    5758            try:
  • AUTHORS

     
    7575    Chris Cahoon <chris.cahoon@gmail.com>
    7676    Juan Manuel Caicedo <juan.manuel.caicedo@gmail.com>
    7777    Trevor Caira <trevor@caira.com>
     78    Brett Cannon <brett@python.org>
    7879    Ricardo Javier Cárdenes Medina <ricardo.cardenes@gmail.com>
    7980    Jeremy Carbaugh <jcarbaugh@gmail.com>
    8081    carljm <carl@dirtcircle.com>
Back to Top