Ticket #8193: import_fixes-with-sys.modules.diff

File import_fixes-with-sys.modules.diff, 19.1 KB (added by mrts, 10 years ago)

patch with the sys.modules[modname] idiom, against trunk

  • django/test/client.py

     
    172172        Obtains the current session variables.
    173173        """
    174174        if 'django.contrib.sessions' in settings.INSTALLED_APPS:
    175             engine = __import__(settings.SESSION_ENGINE, {}, {}, [''])
     175            __import__(settings.SESSION_ENGINE)
     176            engine = sys.modules[settings.SESSION_ENGINE]
    176177            cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None)
    177178            if cookie:
    178179                return engine.SessionStore(cookie.value)
     
    374375        user = authenticate(**credentials)
    375376        if user and user.is_active \
    376377                and 'django.contrib.sessions' in settings.INSTALLED_APPS:
    377             engine = __import__(settings.SESSION_ENGINE, {}, {}, [''])
     378            __import__(settings.SESSION_ENGINE)
     379            engine = sys.modules[settings.SESSION_ENGINE]
    378380
    379381            # Create a fake request to store login details.
    380382            request = HttpRequest()
     
    409411
    410412        Causes the authenticated user to be logged out.
    411413        """
    412         session = __import__(settings.SESSION_ENGINE, {}, {}, ['']).SessionStore()
     414        __import__(settings.SESSION_ENGINE)
     415        session = sys.modules[settings.SESSION_ENGINE].SessionStore()
    413416        session.delete(session_key=self.cookies[settings.SESSION_COOKIE_NAME].value)
    414417        self.cookies = SimpleCookie()
  • django/conf/__init__.py

     
    66a list of all possible variables.
    77"""
    88
    9 import os
     9import sys, os
    1010import time     # Needed for Windows
    1111from django.conf import global_settings
    1212
     
    8989        self.SETTINGS_MODULE = settings_module
    9090
    9191        try:
    92             mod = __import__(self.SETTINGS_MODULE, {}, {}, [''])
     92            __import__(self.SETTINGS_MODULE)
     93            mod = sys.modules[self.SETTINGS_MODULE]
    9394        except ImportError, e:
    9495            raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
    9596
     
    109110        new_installed_apps = []
    110111        for app in self.INSTALLED_APPS:
    111112            if app.endswith('.*'):
    112                 appdir = os.path.dirname(__import__(app[:-2], {}, {}, ['']).__file__)
     113                __import__(app[:-2])
     114                appdir = os.path.dirname(sys.modules[app[:-2]].__file__)
    113115                app_subdirs = os.listdir(appdir)
    114116                app_subdirs.sort()
    115117                for d in app_subdirs:
  • django/db/__init__.py

     
    1 import os
     1import sys, os
    22from django.conf import settings
    33from django.core import signals
    44from django.core.exceptions import ImproperlyConfigured
     
    1313    # Most of the time, the database backend will be one of the official
    1414    # backends that ships with Django, so look there first.
    1515    _import_path = 'django.db.backends.'
    16     backend = __import__('%s%s.base' % (_import_path, settings.DATABASE_ENGINE), {}, {}, [''])
     16    _mod_name = '%s%s.base' % (_import_path, settings.DATABASE_ENGINE)
     17    __import__(_mod_name)
     18    backend = sys.modules[_mod_name]
    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        _mod_name = '%s.base' % settings.DATABASE_ENGINE
     25        __import__(_mod_name)
     26        backend = sys.modules[_mod_name]
    2327    except ImportError, e_user:
    2428        # The database backend wasn't found. Display a helpful error message
    2529        # listing all possible (built-in) database backends.
  • django/core/serializers/__init__.py

     
    1616
    1717"""
    1818
     19import sys
    1920from django.conf import settings
    2021
    2122# Built-in serializers
     
    3536_serializers = {}
    3637
    3738def register_serializer(format, serializer_module, serializers=None):
    38     """"Register a new serializer. 
    39    
     39    """"Register a new serializer.
     40
    4041    ``serializer_module`` should be the fully qualified module name
    4142    for the serializer.
    42    
     43
    4344    If ``serializers`` is provided, the registration will be added
    4445    to the provided dictionary.
    45    
     46
    4647    If ``serializers`` is not provided, the registration will be made
    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    __import__(serializer_module)
     52    module = sys.modules[serializer_module]
    5153    if serializers is None:
    5254        _serializers[format] = module
    5355    else:
    5456        serializers[format] = module
    55        
     57
    5658def unregister_serializer(format):
    5759    "Unregister a given serializer. This is not a thread-safe operation."
    5860    del _serializers[format]
  • django/core/urlresolvers.py

     
    77    (view_function, function_args, function_kwargs)
    88"""
    99
    10 import re
     10import sys, re
    1111
    1212from django.http import Http404
    1313from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist
     
    5454            lookup_view = lookup_view.encode('ascii')
    5555            mod_name, func_name = get_mod_func(lookup_view)
    5656            if func_name != '':
    57                 lookup_view = getattr(__import__(mod_name, {}, {}, ['']), func_name)
     57                __import__(mod_name)
     58                lookup_view = getattr(sys.modules[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):
     
    195196        try:
    196197            return self._urlconf_module
    197198        except AttributeError:
    198             self._urlconf_module = __import__(self.urlconf_name, {}, {}, [''])
     199            __import__(self.urlconf_name)
     200            self._urlconf_module = sys.modules[self.urlconf_name]
    199201            return self._urlconf_module
    200202    urlconf_module = property(_get_urlconf_module)
    201203
     
    207209        callback = getattr(self.urlconf_module, 'handler%s' % view_type)
    208210        mod_name, func_name = get_mod_func(callback)
    209211        try:
    210             return getattr(__import__(mod_name, {}, {}, ['']), func_name), {}
     212            __import__(mod_name)
     213            return getattr(sys.modules[mod_name], func_name), {}
    211214        except (ImportError, AttributeError), e:
    212215            raise ViewDoesNotExist, "Tried %s. Error was: %s" % (callback, str(e))
    213216
  • django/core/handlers/base.py

     
    3535                raise exceptions.ImproperlyConfigured, '%s isn\'t a middleware module' % middleware_path
    3636            mw_module, mw_classname = middleware_path[:dot], middleware_path[dot+1:]
    3737            try:
    38                 mod = __import__(mw_module, {}, {}, [''])
     38                __import__(mw_module)
     39                mod = sys.modules[mw_module]
    3940            except ImportError, e:
    4041                raise exceptions.ImproperlyConfigured, 'Error importing middleware %s: "%s"' % (mw_module, e)
    4142            try:
  • django/core/files/storage.py

     
    1 import os
     1import sys, os
    22import errno
    33import urlparse
    44
     
    219219        raise ImproperlyConfigured("%s isn't a storage module." % import_path)
    220220    module, classname = import_path[:dot], import_path[dot+1:]
    221221    try:
    222         mod = __import__(module, {}, {}, [''])
     222        __import__(module)
     223        mod = sys.modules[module]
    223224    except ImportError, e:
    224225        raise ImproperlyConfigured('Error importing storage module %s: "%s"' % (module, e))
    225226    try:
  • django/core/cache/__init__.py

     
    1515See docs/cache.txt for information on the public API.
    1616"""
    1717
     18import sys
    1819from cgi import parse_qsl
    1920from django.conf import settings
    2021from django.core import signals
     
    4950        host = host[:-1]
    5051
    5152    if scheme in BACKENDS:
    52         module = __import__('django.core.cache.backends.%s' % BACKENDS[scheme], {}, {}, [''])
     53        modname = 'django.core.cache.backends.%s' % BACKENDS[scheme]
     54        __import__(modname)
     55        module = sys.modules[modname]
    5356    else:
    54         module = __import__(scheme, {}, {}, [''])
     57        __import__(scheme)
     58        module = sys.modules[scheme]
    5559    return getattr(module, 'CacheClass')(host, params)
    5660
    5761cache = get_cache(settings.CACHE_BACKEND)
  • django/core/management/commands/flush.py

     
    2323        # dispatcher events.
    2424        for app_name in settings.INSTALLED_APPS:
    2525            try:
    26                 __import__(app_name + '.management', {}, {}, [''])
     26                __import__(app_name + '.management')
    2727            except ImportError:
    2828                pass
    2929
  • django/core/management/commands/syncdb.py

     
    3030        # dispatcher events.
    3131        for app_name in settings.INSTALLED_APPS:
    3232            try:
    33                 __import__(app_name + '.management', {}, {}, [''])
     33                __import__(app_name + '.management')
    3434            except ImportError, exc:
    3535                # This is slightly hackish. We want to ignore ImportErrors
    3636                # if the "management" module itself is missing -- but we don't
  • django/core/management/__init__.py

     
    104104        # Find the project directory
    105105        try:
    106106            from django.conf import settings
     107            __import__(settings.SETTINGS_MODULE)
    107108            project_directory = setup_environ(
    108                 __import__(
    109                     settings.SETTINGS_MODULE, {}, {},
    110                     (settings.SETTINGS_MODULE.split(".")[-1],)
    111                 ), settings.SETTINGS_MODULE
     109                    sys.modules[settings.SETTINGS_MODULE],
     110                    settings.SETTINGS_MODULE
    112111            )
    113112        except (AttributeError, EnvironmentError, ImportError):
    114113            project_directory = None
     
    313312    project_name = os.path.basename(project_directory)
    314313    settings_name = os.path.splitext(settings_filename)[0]
    315314    sys.path.append(os.path.join(project_directory, os.pardir))
    316     project_module = __import__(project_name, {}, {}, [''])
     315    __import__(project_name)
     316    project_module = sys.modules[project_name]
    317317    sys.path.pop()
    318318
    319319    # Set DJANGO_SETTINGS_MODULE appropriately.
  • django/templatetags/__init__.py

     
     1import sys
    12from django.conf import settings
    23
    34for a in settings.INSTALLED_APPS:
     
    23    try:
    3         __path__.extend(__import__(a + '.templatetags', {}, {}, ['']).__path__)
     4        modname = a + '.templatetags'
     5        __import__(modname)
     6        __path__.extend(sys.modules[modname].__path__)
    47    except ImportError:
  • django/views/i18n.py

     
    22from django.utils.translation import check_for_language, activate, to_locale, get_language
    33from django.utils.text import javascript_quote
    44from django.conf import settings
    5 import os
     5import sys, os
    66import gettext as gettext_module
    77
    88def set_language(request):
     
    128128    paths = []
    129129    # first load all english languages files for defaults
    130130    for package in packages:
    131         p = __import__(package, {}, {}, [''])
     131        __import__(package)
     132        p = sys.modules[package]
    132133        path = os.path.join(os.path.dirname(p.__file__), 'locale')
    133134        paths.append(path)
    134135        try:
  • django/contrib/comments/__init__.py

     
     1import sys
    12from django.conf import settings
    23from django.core import urlresolvers
    34from django.core.exceptions import ImproperlyConfigured
     
    1718
    1819    # Try to import the package
    1920    try:
    20         package = __import__(comments_app, '', '', [''])
     21        __import__(comments_app)
     22        package = sys.modules[comments_app]
    2123    except ImportError:
    2224        raise ImproperlyConfigured("The COMMENTS_APP setting refers to "\
    2325                                   "a non-existing package.")
  • django/contrib/admin/views/template.py

     
     1import sys
    12from django import template, forms
    23from django.contrib.admin.views.decorators import staff_member_required
    34from django.template import loader
     
    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        __import__(mod)
     20        settings_module = sys.modules[mod]
    1921        settings_modules[settings_module.SITE_ID] = settings_module
    2022    site_list = Site.objects.in_bulk(settings_modules.keys()).values()
    2123    if request.POST:
  • django/contrib/admindocs/views.py

     
    1111from django.contrib.sites.models import Site
    1212from django.utils.translation import ugettext as _
    1313from django.utils.safestring import mark_safe
    14 import inspect, os, re
     14import sys, inspect, os, re
    1515
    1616# Exclude methods starting with these strings from documentation
    1717MODEL_METHODS_EXCLUDE = ('_', 'add_', 'delete', 'save', 'set_')
     
    114114        return missing_docutils_page(request)
    115115
    116116    if settings.ADMIN_FOR:
    117         settings_modules = [__import__(m, {}, {}, ['']) for m in settings.ADMIN_FOR]
     117        settings_modules = []
     118        for m in settings.ADMIN_FOR:
     119            __import__(m)
     120            settings_modules.append(sys.modules[m])
    118121    else:
    119122        settings_modules = [settings]
    120123
    121124    views = []
    122125    for settings_mod in settings_modules:
    123         urlconf = __import__(settings_mod.ROOT_URLCONF, {}, {}, [''])
     126        __import__(settings_mod.ROOT_URLCONF)
     127        urlconf = sys.modules[settings_mod.ROOT_URLCONF]
    124128        view_functions = extract_views_from_urlpatterns(urlconf.urlpatterns)
    125129        if Site._meta.installed:
    126130            site_obj = Site.objects.get(pk=settings_mod.SITE_ID)
     
    146150
    147151    mod, func = urlresolvers.get_mod_func(view)
    148152    try:
    149         view_func = getattr(__import__(mod, {}, {}, ['']), func)
     153        __import__(mod)
     154        view_func = getattr(sys.modules[mod], func)
    150155    except (ImportError, AttributeError):
    151156        raise Http404
    152157    title, body, metadata = utils.parse_docstring(view_func.__doc__)
     
    257262def template_detail(request, template):
    258263    templates = []
    259264    for site_settings_module in settings.ADMIN_FOR:
    260         settings_mod = __import__(site_settings_module, {}, {}, [''])
     265        __import__(site_settings_module)
     266        settings_mod = sys.modules[site_settings_module]
    261267        if Site._meta.installed:
    262268            site_obj = Site.objects.get(pk=settings_mod.SITE_ID)
    263269        else:
  • django/contrib/sessions/middleware.py

     
    1 import time
     1import sys, time
    22
    33from django.conf import settings
    44from django.utils.cache import patch_vary_headers
     
    66
    77class SessionMiddleware(object):
    88    def process_request(self, request):
    9         engine = __import__(settings.SESSION_ENGINE, {}, {}, [''])
     9        # FIXME: __import__ on EVERY request?! Move to __init__
     10        __import__(settings.SESSION_ENGINE)
     11        engine = sys.modules[settings.SESSION_ENGINE]
    1012        session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)
    1113        request.session = engine.SessionStore(session_key)
    1214
  • django/template/__init__.py

     
    4848>>> t.render(c)
    4949u'<html></html>'
    5050"""
    51 import re
     51import sys, re
    5252from inspect import getargspec
    5353from django.conf import settings
    5454from django.template.context import Context, RequestContext, ContextPopException
     
    934934    lib = libraries.get(module_name, None)
    935935    if not lib:
    936936        try:
    937             mod = __import__(module_name, {}, {}, [''])
     937            __import__(module_name)
     938            mod = sys.modules[module_name]
    938939        except ImportError, e:
    939940            raise InvalidTemplateLibrary("Could not load template library from %s, %s" % (module_name, e))
    940941        try:
  • tests/regressiontests/dynamic_imports/tests.py

     
     1__test__ = {'API_TESTS': """
     2>>> import sys
     3>>> import os
     4>>> mod_name = os.environ['DJANGO_SETTINGS_MODULE']
     5>>> mod = __import__(mod_name, {}, {}, [mod_name.split('.')[-1]])
     6>>> from django.core.management import setup_environ
     7>>> d = setup_environ(mod)
     8>>> [k for k in sys.modules if k.endswith('.') or '..' in k]
     9[]
     10"""}
Back to Top