Permalink
Browse files

Fixed #21674 -- Deprecated the import_by_path() function in favor of …

…import_string().

Thanks Aymeric Augustin for the suggestion and review.
  • Loading branch information...
1 parent fcc2183 commit 5d263dee304fdaf95e18d2f0619d6925984a7f02 @berkerpeksag berkerpeksag committed with timgraham Jan 20, 2014
View
@@ -484,6 +484,7 @@ answer newbie questions, and generally made Django that much better:
John Paulett <john@paulett.org>
pavithran s <pavithran.s@gmail.com>
Barry Pederson <bp@barryp.org>
+ Berker Peksag <berker.peksag@gmail.com>
Andreas Pelme <andreas@pelme.se>
permonik@mesias.brnonet.cz
peter@mymart.com
@@ -2,7 +2,7 @@
from unittest import SkipTest
from django.contrib.staticfiles.testing import StaticLiveServerCase
-from django.utils.module_loading import import_by_path
+from django.utils.module_loading import import_string
from django.utils.translation import ugettext as _
@@ -22,7 +22,7 @@ def setUpClass(cls):
if not os.environ.get('DJANGO_SELENIUM_TESTS', False):
raise SkipTest('Selenium tests not requested')
try:
- cls.selenium = import_by_path(cls.webdriver_class)()
+ cls.selenium = import_string(cls.webdriver_class)()
except Exception as e:
raise SkipTest('Selenium webdriver "%s" not installed or not '
'operational: %s' % (cls.webdriver_class, str(e)))
@@ -4,7 +4,7 @@
from django.apps import apps as django_apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured, PermissionDenied
-from django.utils.module_loading import import_by_path
+from django.utils.module_loading import import_string
from django.middleware.csrf import rotate_token
from .signals import user_logged_in, user_logged_out, user_login_failed
@@ -15,7 +15,7 @@
def load_backend(path):
- return import_by_path(path)()
+ return import_string(path)()
def get_backends():
@@ -13,7 +13,7 @@
from django.core.exceptions import ImproperlyConfigured
from django.utils.crypto import (
pbkdf2, constant_time_compare, get_random_string)
-from django.utils.module_loading import import_by_path
+from django.utils.module_loading import import_string
from django.utils.translation import ugettext_noop as _
@@ -92,7 +92,7 @@ def load_hashers(password_hashers=None):
if not password_hashers:
password_hashers = settings.PASSWORD_HASHERS
for backend in password_hashers:
- hasher = import_by_path(backend)()
+ hasher = import_string(backend)()
if not getattr(hasher, 'algorithm'):
raise ImproperlyConfigured("hasher doesn't specify an "
"algorithm name: %s" % backend)
@@ -58,7 +58,7 @@ def process_request(self, request):
auth.BACKEND_SESSION_KEY, ''))
if isinstance(stored_backend, RemoteUserBackend):
auth.logout(request)
- except ImproperlyConfigured:
+ except ImportError:
# backend failed to load
auth.logout(request)
return
@@ -1,5 +1,4 @@
-from django.core.exceptions import ImproperlyConfigured
-from django.utils.module_loading import import_by_path
+from django.utils.module_loading import import_string
from django.contrib.formtools.wizard.storage.base import BaseStorage
from django.contrib.formtools.wizard.storage.exceptions import (
@@ -12,7 +11,7 @@
def get_storage(path, *args, **kwargs):
try:
- storage_class = import_by_path(path)
- except ImproperlyConfigured as e:
+ storage_class = import_string(path)
+ except ImportError as e:
raise MissingStorage('Error loading storage: %s' % e)
return storage_class(*args, **kwargs)
@@ -1,12 +1,12 @@
from django.conf import settings
-from django.utils.module_loading import import_by_path
+from django.utils.module_loading import import_string
def default_storage(request):
"""
Callable with the same interface as the storage classes.
- This isn't just default_storage = import_by_path(settings.MESSAGE_STORAGE)
+ This isn't just default_storage = import_string(settings.MESSAGE_STORAGE)
to avoid accessing the settings at the module level.
"""
- return import_by_path(settings.MESSAGE_STORAGE)(request)
+ return import_string(settings.MESSAGE_STORAGE)(request)
@@ -12,7 +12,7 @@
from django.utils.crypto import salted_hmac
from django.utils import timezone
from django.utils.encoding import force_bytes, force_text
-from django.utils.module_loading import import_by_path
+from django.utils.module_loading import import_string
from django.contrib.sessions.exceptions import SuspiciousSession
@@ -40,7 +40,7 @@ def __init__(self, session_key=None):
self._session_key = session_key
self.accessed = False
self.modified = False
- self.serializer = import_by_path(settings.SESSION_SERIALIZER)
+ self.serializer = import_string(settings.SESSION_SERIALIZER)
def __contains__(self, key):
return key in self._session
@@ -6,7 +6,7 @@
from django.core.exceptions import ImproperlyConfigured
from django.core.files.storage import default_storage, Storage, FileSystemStorage
from django.utils.functional import empty, LazyObject
-from django.utils.module_loading import import_by_path
+from django.utils.module_loading import import_string
from django.utils._os import safe_join
from django.utils import six, lru_cache
@@ -257,7 +257,7 @@ def get_finder(import_path):
Imports the staticfiles finder class described by import_path, where
import_path is the full Python path to the class.
"""
- Finder = import_by_path(import_path)
+ Finder = import_string(import_path)
if not issubclass(Finder, BaseFinder):
raise ImproperlyConfigured('Finder "%s" is not a subclass of "%s"' %
(Finder, BaseFinder))
@@ -20,7 +20,7 @@
from django.core.cache.backends.base import (
InvalidCacheBackendError, CacheKeyWarning, BaseCache)
from django.core.exceptions import ImproperlyConfigured
-from django.utils.module_loading import import_by_path
+from django.utils.module_loading import import_string
__all__ = [
@@ -69,8 +69,8 @@ def _create_cache(backend, **kwargs):
except KeyError:
try:
# Trying to import the given backend, in case it's a dotted path
- import_by_path(backend)
- except ImproperlyConfigured as e:
+ import_string(backend)
+ except ImportError as e:
raise InvalidCacheBackendError("Could not find backend '%s': %s" % (
backend, e))
location = kwargs.pop('LOCATION', '')
@@ -80,8 +80,8 @@ def _create_cache(backend, **kwargs):
params.update(kwargs)
backend = params.pop('BACKEND')
location = params.pop('LOCATION', '')
- backend_cls = import_by_path(backend)
- except (AttributeError, ImportError, ImproperlyConfigured) as e:
+ backend_cls = import_string(backend)
+ except ImportError as e:
raise InvalidCacheBackendError(
"Could not find backend '%s': %s" % (backend, e))
return backend_cls(location, params)
@@ -5,7 +5,7 @@
import warnings
from django.core.exceptions import ImproperlyConfigured, DjangoRuntimeWarning
-from django.utils.module_loading import import_by_path
+from django.utils.module_loading import import_string
class InvalidCacheBackendError(ImproperlyConfigured):
@@ -45,7 +45,7 @@ def get_key_func(key_func):
if callable(key_func):
return key_func
else:
- return import_by_path(key_func)
+ return import_string(key_func)
return default_key_func
@@ -9,7 +9,7 @@
from django.core.files.move import file_move_safe
from django.utils.encoding import force_text, filepath_to_uri
from django.utils.functional import LazyObject
-from django.utils.module_loading import import_by_path
+from django.utils.module_loading import import_string
from django.utils.six.moves.urllib.parse import urljoin
from django.utils.text import get_valid_filename
from django.utils._os import safe_join, abspathu
@@ -301,7 +301,7 @@ def modified_time(self, name):
def get_storage_class(import_path=None):
- return import_by_path(import_path or settings.DEFAULT_FILE_STORAGE)
+ return import_string(import_path or settings.DEFAULT_FILE_STORAGE)
class DefaultStorage(LazyObject):
@@ -9,7 +9,7 @@
from django.conf import settings
from django.core.files.uploadedfile import TemporaryUploadedFile, InMemoryUploadedFile
from django.utils.encoding import python_2_unicode_compatible
-from django.utils.module_loading import import_by_path
+from django.utils.module_loading import import_string
__all__ = [
'UploadFileException', 'StopUpload', 'SkipFile', 'FileUploadHandler',
@@ -214,4 +214,4 @@ def load_handler(path, *args, **kwargs):
<TemporaryFileUploadHandler object at 0x...>
"""
- return import_by_path(path)(*args, **kwargs)
+ return import_string(path)(*args, **kwargs)
@@ -11,7 +11,7 @@
from django.core.exceptions import MiddlewareNotUsed, PermissionDenied, SuspiciousOperation
from django.db import connections, transaction
from django.utils.encoding import force_text
-from django.utils.module_loading import import_by_path
+from django.utils.module_loading import import_string
from django.utils import six
from django.views import debug
@@ -43,7 +43,7 @@ def load_middleware(self):
request_middleware = []
for middleware_path in settings.MIDDLEWARE_CLASSES:
- mw_class = import_by_path(middleware_path)
+ mw_class = import_string(middleware_path)
try:
mw_instance = mw_class()
except MiddlewareNotUsed:
@@ -4,7 +4,7 @@
from __future__ import unicode_literals
from django.conf import settings
-from django.utils.module_loading import import_by_path
+from django.utils.module_loading import import_string
# Imported for backwards compatibility, and for the sake
# of a cleaner namespace. These symbols used to be in
@@ -34,7 +34,7 @@ def get_connection(backend=None, fail_silently=False, **kwds):
Both fail_silently and other keyword arguments are used in the
constructor of the backend.
"""
- klass = import_by_path(backend or settings.EMAIL_BACKEND)
+ klass = import_string(backend or settings.EMAIL_BACKEND)
return klass(fail_silently=fail_silently, **kwds)
@@ -16,9 +16,11 @@
from wsgiref import simple_server
from wsgiref.util import FileWrapper # NOQA: for backwards compatibility
+from django.core.exceptions import ImproperlyConfigured
from django.core.management.color import color_style
from django.core.wsgi import get_wsgi_application
-from django.utils.module_loading import import_by_path
+from django.utils import six
+from django.utils.module_loading import import_string
from django.utils.six.moves import socketserver
__all__ = ('WSGIServer', 'WSGIRequestHandler', 'MAX_SOCKET_CHUNK_SIZE')
@@ -50,10 +52,18 @@ def get_internal_wsgi_application():
if app_path is None:
return get_wsgi_application()
- return import_by_path(
- app_path,
- error_prefix="WSGI application '%s' could not be loaded; " % app_path
- )
+ try:
+ return import_string(app_path)
+ except ImportError as e:
+ msg = (
+ "WSGI application '%(app_path)s' could not be loaded; "
+ "Error importing module: '%(exception)s'" % ({
+ 'app_path': app_path,
+ 'exception': e,
+ })
+ )
+ six.reraise(ImproperlyConfigured, ImproperlyConfigured(msg),
+ sys.exc_info()[2])
class ServerHandler(simple_server.ServerHandler, object):
@@ -44,7 +44,7 @@
from django.utils import baseconv
from django.utils.crypto import constant_time_compare, salted_hmac
from django.utils.encoding import force_bytes, force_str, force_text
-from django.utils.module_loading import import_by_path
+from django.utils.module_loading import import_string
class BadSignature(Exception):
@@ -75,7 +75,7 @@ def base64_hmac(salt, value, key):
def get_cookie_signer(salt='django.core.signing.get_cookie_signer'):
- Signer = import_by_path(settings.SIGNING_BACKEND)
+ Signer = import_string(settings.SIGNING_BACKEND)
return Signer('django.http.cookies' + settings.SECRET_KEY, salt=salt)
@@ -3,7 +3,7 @@
from django.db import models
from django.db.models.options import DEFAULT_NAMES, normalize_unique_together
from django.utils import six
-from django.utils.module_loading import import_by_path
+from django.utils.module_loading import import_string
class InvalidBasesError(ValueError):
@@ -115,7 +115,7 @@ def from_model(cls, model):
fields = []
for field in model._meta.local_fields:
name, path, args, kwargs = field.deconstruct()
- field_class = import_by_path(path)
+ field_class = import_string(path)
try:
fields.append((name, field_class(*args, **kwargs)))
except TypeError as e:
@@ -127,7 +127,7 @@ def from_model(cls, model):
))
for field in model._meta.local_many_to_many:
name, path, args, kwargs = field.deconstruct()
- field_class = import_by_path(path)
+ field_class = import_string(path)
try:
fields.append((name, field_class(*args, **kwargs)))
except TypeError as e:
@@ -175,7 +175,7 @@ def clone(self):
fields = []
for name, field in self.fields:
_, path, args, kwargs = field.deconstruct()
- field_class = import_by_path(path)
+ field_class = import_string(path)
fields.append((name, field_class(*args, **kwargs)))
# Now make a copy
return self.__class__(
View
@@ -7,7 +7,7 @@
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.functional import cached_property
-from django.utils.module_loading import import_by_path
+from django.utils.module_loading import import_string
from django.utils._os import upath
from django.utils import six
@@ -221,7 +221,7 @@ def routers(self):
routers = []
for r in self._routers:
if isinstance(r, six.string_types):
- router = import_by_path(r)()
+ router = import_string(r)()
else:
router = r
routers.append(router)
@@ -1,5 +1,5 @@
from copy import copy
-from django.utils.module_loading import import_by_path
+from django.utils.module_loading import import_string
# Cache of actual callables.
_standard_context_processors = None
@@ -162,7 +162,7 @@ def get_standard_processors():
collect.extend(_builtin_context_processors)
collect.extend(settings.TEMPLATE_CONTEXT_PROCESSORS)
for path in collect:
- func = import_by_path(path)
+ func = import_string(path)
processors.append(func)
_standard_context_processors = tuple(processors)
return _standard_context_processors
@@ -28,7 +28,7 @@
from django.core.exceptions import ImproperlyConfigured
from django.template.base import Origin, Template, Context, TemplateDoesNotExist
from django.conf import settings
-from django.utils.module_loading import import_by_path
+from django.utils.module_loading import import_string
from django.utils import six
template_source_loaders = None
@@ -95,7 +95,7 @@ def find_template_loader(loader):
else:
args = []
if isinstance(loader, six.string_types):
- TemplateLoader = import_by_path(loader)
+ TemplateLoader = import_string(loader)
if hasattr(TemplateLoader, 'load_template_source'):
func = TemplateLoader(*args)
Oops, something went wrong. Retry.

0 comments on commit 5d263de

Please sign in to comment.