django.utils.module_loading.import_string

Here are the examples of the python api django.utils.module_loading.import_string taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: PyClassLessons
Source File: tests.py
View license
    @classmethod
    def setUpClass(cls):
        if not os.environ.get('DJANGO_SELENIUM_TESTS', False):
            raise SkipTest('Selenium tests not requested')
        try:
            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)))
        # This has to be last to ensure that resources are cleaned up properly!
        super(AdminSeleniumWebDriverTestCase, cls).setUpClass()

Example 2

Project: PyClassLessons
Source File: finders.py
View license
@lru_cache.lru_cache(maxsize=None)
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_string(import_path)
    if not issubclass(Finder, BaseFinder):
        raise ImproperlyConfigured('Finder "%s" is not a subclass of "%s"' %
                                   (Finder, BaseFinder))
    return Finder()

Example 3

Project: PyClassLessons
Source File: base.py
View license
def get_key_func(key_func):
    """
    Function to decide which key function to use.

    Defaults to ``default_key_func``.
    """
    if key_func is not None:
        if callable(key_func):
            return key_func
        else:
            return import_string(key_func)
    return default_key_func

Example 4

Project: PyClassLessons
Source File: uploadhandler.py
View license
def load_handler(path, *args, **kwargs):
    """
    Given a path to a handler, return an instance of that handler.

    E.g.::
        >>> from django.http import HttpRequest
        >>> request = HttpRequest()
        >>> load_handler('django.core.files.uploadhandler.TemporaryFileUploadHandler', request)
        <TemporaryFileUploadHandler object at 0x...>

    """
    return import_string(path)(*args, **kwargs)

Example 5

Project: PyClassLessons
Source File: __init__.py
View license
def get_connection(backend=None, fail_silently=False, **kwds):
    """Load an email backend and return an instance of it.

    If backend is None (default) settings.EMAIL_BACKEND is used.

    Both fail_silently and other keyword arguments are used in the
    constructor of the backend.
    """
    klass = import_string(backend or settings.EMAIL_BACKEND)
    return klass(fail_silently=fail_silently, **kwds)

Example 6

Project: PyClassLessons
Source File: state.py
View license
    def construct_fields(self):
        "Deep-clone the fields using deconstruction"
        for name, field in self.fields:
            _, path, args, kwargs = field.deconstruct()
            field_class = import_string(path)
            yield name, field_class(*args, **kwargs)

Example 7

Project: PyClassLessons
Source File: log.py
View license
def configure_logging(logging_config, logging_settings):
    if not sys.warnoptions:
        # Route warnings through python logging
        logging.captureWarnings(True)
        # RemovedInNextVersionWarning is a subclass of DeprecationWarning which
        # is hidden by default, hence we force the "default" behavior
        warnings.simplefilter("default", RemovedInNextVersionWarning)

    if logging_config:
        # First find the logging configuration function ...
        logging_config_func = import_string(logging_config)

        logging_config_func(DEFAULT_LOGGING)

        # ... then invoke it with the logging settings
        if logging_settings:
            logging_config_func(logging_settings)

Example 8

Project: PyClassLessons
Source File: debug.py
View license
def get_exception_reporter_filter(request):
    global default_exception_reporter_filter
    if default_exception_reporter_filter is None:
        # Load the default filter for the first time and cache it.
        default_exception_reporter_filter = import_string(
            settings.DEFAULT_EXCEPTION_REPORTER_FILTER)()
    if request:
        return getattr(request, 'exception_reporter_filter', default_exception_reporter_filter)
    else:
        return default_exception_reporter_filter

Example 9

Project: myks-gallery
Source File: storages.py
View license
@lru_cache()
def get_storage(name):
    name = name.upper()
    storage_setting = 'GALLERY_{}_STORAGE'.format(name)
    dir_setting = 'GALLERY_{}_DIR'.format(name)
    try:
        storage_class = getattr(settings, storage_setting)
    except AttributeError:
        # There's a good chance that this fallback will survive for a long
        # time because deprecating it would require updating all the tests.
        try:
            storage_dir = getattr(settings, dir_setting)
        except AttributeError:
            raise ImproperlyConfigured(
                "Please define {} or {}".format(storage_setting, dir_setting))
        else:
            return FileSystemStorage(location=storage_dir)
    else:
        return import_string(storage_class)()

Example 10

Project: django-shop
Source File: auth.py
View license
    def render(self, context, instance, placeholder):
        """
        Return the context to render a DialogFormPlugin
        """
        form_type = instance.glossary.get('form_type')
        if form_type:
            # prevent a malicious database entry to import an ineligible file
            form_type = AUTH_FORM_TYPES[[ft[0] for ft in AUTH_FORM_TYPES].index(form_type)]
            try:
                FormClass = import_string(form_type[2])
            except (ImportError, IndexError):
                # TODO: other unresolvable may need another form name
                context['form_name'] = 'auth_form'
            else:
                context['form_name'] = FormClass.form_name
                context[FormClass.form_name] = FormClass()
        context['action'] = instance.link
        return super(ShopAuthenticationPlugin, self).render(context, instance, placeholder)

Example 11

Project: django-shop
Source File: order.py
View license
    def __new__(cls, name, bases, attrs):
        if 'BaseOrder' in (b.__name__ for b in bases):
            bases = tuple(import_string(mc) for mc in shop_settings.ORDER_WORKFLOWS) + bases
            # merge the dicts of TRANSITION_TARGETS
            attrs.update(_transition_targets={}, _auto_transitions={})
            for b in reversed(bases):
                TRANSITION_TARGETS = getattr(b, 'TRANSITION_TARGETS', {})
                delattr(b, 'TRANSITION_TARGETS')
                if set(TRANSITION_TARGETS.keys()).intersection(attrs['_transition_targets']):
                    msg = "Mixin class {} already contains a transition named '{}'"
                    raise ImproperlyConfigured(msg.format(b.__name__, ', '.join(TRANSITION_TARGETS.keys())))
                attrs['_transition_targets'].update(TRANSITION_TARGETS)
                attrs['_auto_transitions'].update(cls.add_to_auto_transitions(b))
        Model = super(WorkflowMixinMetaclass, cls).__new__(cls, name, bases, attrs)
        return Model

Example 12

Project: django-shop
Source File: pool.py
View license
    def get_all_modifiers(self):
        """
        Returns all registered modifiers of this shop instance.
        """
        if not self.USE_CACHE or not self._modifiers_list:
            self._modifiers_list = [import_string(mc)() for mc in settings.CART_MODIFIERS]
        return self._modifiers_list

Example 13

Project: django-shop
Source File: checkout.py
View license
    def __init__(self, **kwargs):
        super(CheckoutViewSet, self).__init__(**kwargs)
        self.dialog_forms = []
        for p in plugin_pool.get_all_plugins():
            if issubclass(p, DialogFormPluginBase):
                self.dialog_forms.append(import_string(p.form_class))

Example 14

Project: readthedocs.org
Source File: backends.py
View license
def send_notification(request, notification):
    """Send notifications through all backends defined by settings

    Backends should be listed in the settings ``NOTIFICATION_BACKENDS``, which
    should be a list of class paths to be loaded, using the standard Django
    string module loader.
    """
    backends = getattr(settings, 'NOTIFICATION_BACKENDS', [])
    for cls_name in backends:
        backend = import_string(cls_name)(request)
        backend.send(notification)

Example 15

Project: django-smsish
Source File: __init__.py
View license
def get_sms_connection(backend=None, fail_silently=False, **kwds):
	"""Load an sms backend and return an instance of it.

	If backend is None (default) settings.SMS_BACKEND is used.

	Both fail_silently and other keyword arguments are used in the
	constructor of the backend.

	https://github.com/django/django/blob/master/django/core/mail/__init__.py#L28
	"""
	klass = import_string(backend or settings.SMS_BACKEND)
	return klass(fail_silently=fail_silently, **kwds)

Example 16

Project: Django--an-app-at-a-time
Source File: hashers.py
View license
@lru_cache.lru_cache()
def get_hashers():
    hashers = []
    for hasher_path in settings.PASSWORD_HASHERS:
        hasher_cls = import_string(hasher_path)
        hasher = hasher_cls()
        if not getattr(hasher, 'algorithm'):
            raise ImproperlyConfigured("hasher doesn't specify an "
                                       "algorithm name: %s" % hasher_path)
        hashers.append(hasher)
    return hashers

Example 17

View license
def default_storage(request):
    """
    Callable with the same interface as the storage classes.

    This isn't just default_storage = import_string(settings.MESSAGE_STORAGE)
    to avoid accessing the settings at the module level.
    """
    return import_string(settings.MESSAGE_STORAGE)(request)

Example 18

Project: Django--an-app-at-a-time
Source File: finders.py
View license
@lru_cache.lru_cache(maxsize=None)
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_string(import_path)
    if not issubclass(Finder, BaseFinder):
        raise ImproperlyConfigured('Finder "%s" is not a subclass of "%s"' %
                                   (Finder, BaseFinder))
    return Finder()

Example 19

Project: Django--an-app-at-a-time
Source File: base.py
View license
def get_key_func(key_func):
    """
    Function to decide which key function to use.

    Defaults to ``default_key_func``.
    """
    if key_func is not None:
        if callable(key_func):
            return key_func
        else:
            return import_string(key_func)
    return default_key_func

Example 20

View license
def get_connection(backend=None, fail_silently=False, **kwds):
    """Load an email backend and return an instance of it.

    If backend is None (default) settings.EMAIL_BACKEND is used.

    Both fail_silently and other keyword arguments are used in the
    constructor of the backend.
    """
    klass = import_string(backend or settings.EMAIL_BACKEND)
    return klass(fail_silently=fail_silently, **kwds)

Example 21

Project: Django--an-app-at-a-time
Source File: state.py
View license
    def construct_managers(self):
        "Deep-clone the managers using deconstruction"
        # Sort all managers by their creation counter
        sorted_managers = sorted(self.managers, key=lambda v: v[1].creation_counter)
        for mgr_name, manager in sorted_managers:
            as_manager, manager_path, qs_path, args, kwargs = manager.deconstruct()
            if as_manager:
                qs_class = import_string(qs_path)
                yield mgr_name, qs_class.as_manager()
            else:
                manager_class = import_string(manager_path)
                yield mgr_name, manager_class(*args, **kwargs)

Example 22

Project: Django--an-app-at-a-time
Source File: utils.py
View license
    @cached_property
    def routers(self):
        if self._routers is None:
            self._routers = settings.DATABASE_ROUTERS
        routers = []
        for r in self._routers:
            if isinstance(r, six.string_types):
                router = import_string(r)()
            else:
                router = r
            routers.append(router)
        return routers

Example 23

Project: Django--an-app-at-a-time
Source File: jinja2.py
View license
    def __init__(self, params):
        params = params.copy()
        options = params.pop('OPTIONS').copy()
        super(Jinja2, self).__init__(params)

        environment = options.pop('environment', 'jinja2.Environment')
        environment_cls = import_string(environment)

        options.setdefault('autoescape', True)
        options.setdefault('loader', jinja2.FileSystemLoader(self.template_dirs))
        options.setdefault('auto_reload', settings.DEBUG)
        options.setdefault('undefined',
                           jinja2.DebugUndefined if settings.DEBUG else jinja2.Undefined)

        self.env = environment_cls(**options)

Example 24

Project: django-filebrowser
Source File: utils.py
View license
def process_image(source, processor_options, processors=None):
    """
    Process a source PIL image through a series of image processors, returning
    the (potentially) altered image.
    """
    global _default_processors
    if processors is None:
        if _default_processors is None:
            _default_processors = [import_string(name) for name in VERSION_PROCESSORS]
        processors = _default_processors
    image = source
    for processor in processors:
        image = processor(image, **processor_options)
    return image

Example 25

Project: callisto-core
Source File: hashers.py
View license
def get_hashers():
    hashers = []
    for hasher_path in settings.KEY_HASHERS:
        hasher_cls = import_string(hasher_path)
        hasher = hasher_cls()
        if not getattr(hasher, 'algorithm'):
            raise ImproperlyConfigured("hasher doesn't specify an algorithm name: {}".format(hasher_path))
        hashers.append(hasher)
    return hashers

Example 26

Project: oioioi
Source File: fields.py
View license
    def validate(self, value, model_instance):
        try:
            obj = import_string(value)
        except Exception:
            raise ValidationError(_("Object %s not found") % (value,))

        superclass = self._get_superclass()
        if not issubclass(obj, superclass):
            raise ValidationError(_("%(value)s is not a %(class_name)s")
                    % dict(value=value, class_name=superclass.__name__))

        if getattr(obj, 'abstract', False):
            raise ValidationError(_("%s is an abstract class and cannot be "
                "used") % (value,))

Example 27

Project: oioioi
Source File: menu.py
View license
    def render(self, context):
        request = context['request']
        registry = self.registry.resolve(context)
        if not registry:
            registry = menu_registry
        if isinstance(registry, basestring):
            registry = import_string(registry)
        if not isinstance(registry, MenuRegistry):
            raise TemplateSyntaxError("{%% generate_menu %%} got an "
                    "argument which is not a MenuRegistry: %r" % (registry,))
        context['menu'] = registry.template_context(request)
        return ''

Example 28

Project: oioioi
Source File: __init__.py
View license
def _run_phase(env, phase, extra_kwargs=None):
    phaseName = phase[0]
    handlerName = phase[1]
    if len(phase) not in [2, 3]:
        raise TypeError('Receipt element has length neither 2 nor 3: %r'
                % phase)
    if len(phase) == 2:
        kwargs = {}
    if len(phase) == 3:
        kwargs = phase[2].copy()
    if extra_kwargs:
        kwargs.update(extra_kwargs)
    handler_func = import_string(handlerName)
    env = handler_func(env, **kwargs)
    if env is None:
        raise RuntimeError('Evaluation handler "%s" (%s) '
            'forgot to return the environment.' % (phaseName,
            handlerName))
    return env

Example 29

Project: oioioi
Source File: addproblem.py
View license
    @transaction.atomic
    def handle(self, *args, **options):
        if not args:
            raise CommandError(_("Missing argument (filename)"))
        if len(args) > 1:
            raise CommandError(_("Expected only one argument"))

        filename = args[0]
        if not os.path.exists(filename):
            raise CommandError(_("File not found: ") + filename)
        try:
            backend = \
                    import_string(backend_for_package(filename))()
        except NoBackend:
            raise CommandError(_("Package format not recognized"))

        problem = backend.simple_unpack(filename)
        self.stdout.write('%d\n' % (problem.id,))

Example 30

Project: oioioi
Source File: package.py
View license
def backend_for_package(filename, original_filename=None):
    """Finds a backend suitable for unpacking the given package and returns
       its dotted name.

       :param filename: a path to the processed problem package

       :param original_filename: the name of the package specified by the
       uploading user.
    """
    for backend_name in settings.PROBLEM_PACKAGE_BACKENDS:
        try:
            backend = import_string(backend_name)()
            if backend.identify(filename, original_filename):
                return backend_name
        # pylint: disable=broad-except
        except Exception:
            logger.warning('Backend %s probe failed', backend_name,
                    exc_info=True)
    raise NoBackend('Problem pack format not recognized')

Example 31

Project: oioioi
Source File: problem_sources.py
View license
@memoized
def problem_sources(request):
    sources = []
    for name in settings.PROBLEM_SOURCES:
        obj = import_string(name)()
        if isinstance(obj, ProblemSource):
            sources.append(obj)
        else:
            for item in obj:
                sources.append(item)
    sources = [s for s in sources if s.is_available(request)]
    return sources

Example 32

Project: betty-cropper
Source File: flush.py
View license
def get_cache_flusher():
    if settings.BETTY_CACHE_FLUSHER:
        if callable(settings.BETTY_CACHE_FLUSHER):
            return settings.BETTY_CACHE_FLUSHER
        else:
            return import_string(settings.BETTY_CACHE_FLUSHER)

Example 33

Project: wagtail
Source File: rich_text.py
View license
def get_rich_text_editor_widget(name='default'):
    editor_settings = getattr(settings, 'WAGTAILADMIN_RICH_TEXT_EDITORS', DEFAULT_RICH_TEXT_EDITORS)

    editor = editor_settings[name]
    options = editor.get('OPTIONS', None)

    if options is None:
        return import_string(editor['WIDGET'])()

    return import_string(editor['WIDGET'])(options=options)

Example 34

Project: wagtail
Source File: __init__.py
View license
def import_finder(dotted_path):
    """
    Imports a finder function from a dotted path. If the dotted path points to a
    module, that module is imported and its "find_embed" function returned.

    If not, this will assume the dotted path points to directly a function and
    will attempt to import that instead.
    """
    try:
        finder_module = import_module(dotted_path)
        return finder_module.find_embed
    except ImportError as e:
        try:
            return import_string(dotted_path)
        except ImportError:
            six.reraise(ImportError, e, sys.exc_info()[2])

Example 35

Project: wagtail
Source File: users.py
View license
def get_custom_user_form(form_setting):
    try:
        return import_string(getattr(settings, form_setting))
    except ImportError:
        raise ImproperlyConfigured(
            "%s refers to a form '%s' that is not available" %
            (form_setting, getattr(settings, form_setting))
        )

Example 36

Project: django-templated-email
Source File: utils.py
View license
def _get_klass_from_config(config_variable, default):
    klass_path = getattr(settings, config_variable, default)
    if isinstance(klass_path, six.string_types):
        klass_path = import_string(klass_path)

    return klass_path

Example 37

Project: django-herald
Source File: models.py
View license
    def resend(self):
        """
        Re-sends the notification by calling the notification class' resend method
        """

        notification_class = import_string(self.notification_class)
        notification_class.resend(self)

Example 38

Project: django-mysql
Source File: cache.py
View license
def get_reverse_key_func(reverse_key_func):
    """
    Function to decide which reverse key function to use

    Defaults to ``None``, as any other value might not apply to the given
    KEY_FUNCTION. Also the user may not use any of the operations that require
    reversing the key_func.
    """
    if reverse_key_func is not None:
        if callable(reverse_key_func):
            return reverse_key_func
        else:
            return import_string(reverse_key_func)
    return None

Example 39

Project: cgstudiomap
Source File: tests.py
View license
    @classmethod
    def setUpClass(cls):
        if not os.environ.get('DJANGO_SELENIUM_TESTS', False):
            raise SkipTest('Selenium tests not requested')
        try:
            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)))
        # This has to be last to ensure that resources are cleaned up properly!
        super(AdminSeleniumWebDriverTestCase, cls).setUpClass()

Example 40

Project: cgstudiomap
Source File: hashers.py
View license
@lru_cache.lru_cache()
def get_hashers():
    hashers = []
    for hasher_path in settings.PASSWORD_HASHERS:
        hasher_cls = import_string(hasher_path)
        hasher = hasher_cls()
        if not getattr(hasher, 'algorithm'):
            raise ImproperlyConfigured("hasher doesn't specify an "
                                       "algorithm name: %s" % hasher_path)
        hashers.append(hasher)
    return hashers

Example 41

Project: cgstudiomap
Source File: password_validation.py
View license
def get_password_validators(validator_config):
    validators = []
    for validator in validator_config:
        try:
            klass = import_string(validator['NAME'])
        except ImportError:
            msg = "The module in NAME could not be imported: %s. Check your AUTH_PASSWORD_VALIDATORS setting."
            raise ImproperlyConfigured(msg % validator['NAME'])
        validators.append(klass(**validator.get('OPTIONS', {})))

    return validators

Example 42

Project: cgstudiomap
Source File: __init__.py
View license
def default_storage(request):
    """
    Callable with the same interface as the storage classes.

    This isn't just default_storage = import_string(settings.MESSAGE_STORAGE)
    to avoid accessing the settings at the module level.
    """
    return import_string(settings.MESSAGE_STORAGE)(request)

Example 43

Project: cgstudiomap
Source File: finders.py
View license
@lru_cache.lru_cache(maxsize=None)
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_string(import_path)
    if not issubclass(Finder, BaseFinder):
        raise ImproperlyConfigured('Finder "%s" is not a subclass of "%s"' %
                                   (Finder, BaseFinder))
    return Finder()

Example 44

Project: cgstudiomap
Source File: base.py
View license
def get_key_func(key_func):
    """
    Function to decide which key function to use.

    Defaults to ``default_key_func``.
    """
    if key_func is not None:
        if callable(key_func):
            return key_func
        else:
            return import_string(key_func)
    return default_key_func

Example 45

Project: cgstudiomap
Source File: uploadhandler.py
View license
def load_handler(path, *args, **kwargs):
    """
    Given a path to a handler, return an instance of that handler.

    E.g.::
        >>> from django.http import HttpRequest
        >>> request = HttpRequest()
        >>> load_handler('django.core.files.uploadhandler.TemporaryFileUploadHandler', request)
        <TemporaryFileUploadHandler object at 0x...>
    """
    return import_string(path)(*args, **kwargs)

Example 46

Project: cgstudiomap
Source File: __init__.py
View license
def get_connection(backend=None, fail_silently=False, **kwds):
    """Load an email backend and return an instance of it.

    If backend is None (default) settings.EMAIL_BACKEND is used.

    Both fail_silently and other keyword arguments are used in the
    constructor of the backend.
    """
    klass = import_string(backend or settings.EMAIL_BACKEND)
    return klass(fail_silently=fail_silently, **kwds)

Example 47

Project: cgstudiomap
Source File: log.py
View license
def configure_logging(logging_config, logging_settings):
    if not sys.warnoptions:
        # Route warnings through python logging
        logging.captureWarnings(True)
        # RemovedInNextVersionWarning is a subclass of DeprecationWarning which
        # is hidden by default, hence we force the "default" behavior
        warnings.simplefilter("default", RemovedInNextVersionWarning)

    if logging_config:
        # First find the logging configuration function ...
        logging_config_func = import_string(logging_config)

        logging.config.dictConfig(DEFAULT_LOGGING)

        # ... then invoke it with the logging settings
        if logging_settings:
            logging_config_func(logging_settings)

Example 48

Project: django-sellmo
Source File: __init__.py
View license
    @cached_property
    def UserChangeForm(self):
        return import_string(
            get_setting(
                'USER_CHANGE_FORM',
                default='%s.internal.forms.UserChangeForm' % __name__
            )
        )

Example 49

Project: django-sellmo
Source File: __init__.py
View license
    @cached_property
    def UserCreationForm(self):
        return import_string(
            get_setting(
                'USER_CREATION_FORM',
                default='%s.internal.forms.UserCreationForm' % __name__
            )
        )

Example 50

Project: django-sellmo
Source File: __init__.py
View license
    @cached_property
    def AuthenticationForm(self):
        return import_string(
            get_setting(
                'AUTHENTICATION_FORM',
                default='django.contrib.auth.forms.AuthenticationForm'
            )
        )