django.utils.importlib.import_module

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

200 Examples 7

Example 1

Project: django-static
Source File: django_static.py
View license
def _load_combine_filenames_generator():
    combine_filenames_generator = getattr(settings, 'DJANGO_STATIC_COMBINE_FILENAMES_GENERATOR', None)
    if combine_filenames_generator:
        from django.utils.importlib import import_module
        _module_name, _function_name = combine_filenames_generator.rsplit('.', 1)
        combine_filenames_generator_module = import_module(_module_name)
        return getattr(combine_filenames_generator_module, _function_name)
    return default_combine_filenames_generator

Example 2

Project: pinax-blog
Source File: utils.py
View license
def load_path_attr(path):
    i = path.rfind(".")
    module, attr = path[:i], path[i + 1:]
    try:
        mod = import_module(module)
    except ImportError as e:
        raise ImproperlyConfigured("Error importing %s: '%s'" % (module, e))
    try:
        attr = getattr(mod, attr)
    except AttributeError:
        raise ImproperlyConfigured("Module '%s' does not define a '%s'" % (module, attr))
    return attr

Example 3

Project: django-mediagenerator
Source File: utils.py
View license
@memoize
def load_backend(path):
    module_name, attr_name = path.rsplit('.', 1)
    try:
        mod = import_module(module_name)
    except (ImportError, ValueError), e:
        raise ImproperlyConfigured('Error importing backend module %s: "%s"' % (module_name, e))
    try:
        return getattr(mod, attr_name)
    except AttributeError:
        raise ImproperlyConfigured('Module "%s" does not define a "%s" backend' % (module_name, attr_name))

Example 4

Project: django-nosqladmin
Source File: mixins.py
View license
    def get_nosqladmins(self):
        """ Returns a list of all nosqladmin implementations for the site 
        """
        nosqladmins = []        
        for nosqladmin in settings.NOSQLADMINS:
            try:
                # TODO - change this to bring in class, not a module
                module = import_module(nosqladmin[0])
            except IndexError:
                raise exceptions.NosqlAdminModuleNotFound(str(nosqladmin))
            
            try:
                nosqladmins.append(module.__dict__[nosqladmin[1]])
            except KeyError:
                raise exceptions.NosqlAdminClassNotFound(str(nosqladmin))
        return nosqladmins

Example 5

Project: django-scaffolding
Source File: __init__.py
View license
def generic_autodiscover(module_name):

    for app in settings.INSTALLED_APPS:
        try:
            import_module(app)
            app_path = sys.modules[app].__path__
        except (AttributeError, ImportError):
            continue
        try:
            imp.find_module(module_name, app_path)
        except ImportError:
            continue
        import_module('%s.%s' % (app, module_name))
        app_path = sys.modules['%s.%s' % (app, module_name)]

Example 6

Project: django-frontendadmin
Source File: views.py
View license
def import_function(s):
    """
    Import a function given the string formatted as
    `module_name.function_name`  (eg `django.utils.text.capfirst`)
    """
    a = s.split('.')
    j = lambda x: '.'.join(x)
    return getattr(import_module(j(a[:-1])), a[-1])

Example 7

Project: django-el-pagination
Source File: loaders.py
View license
def load_object(path):
    """Return the Python object represented by dotted *path*."""
    i = path.rfind('.')
    module_name, object_name = path[:i], path[i + 1:]
    # Load module.
    try:
        module = import_module(module_name)
    except ImportError:
        raise ImproperlyConfigured('Module %r not found' % module_name)
    except ValueError:
        raise ImproperlyConfigured('Invalid module %r' % module_name)
    # Load object.
    try:
        return getattr(module, object_name)
    except AttributeError:
        msg = 'Module %r does not define an object named %r'
        raise ImproperlyConfigured(msg % (module_name, object_name))

Example 8

Project: django-solr
Source File: options.py
View license
    def _prepare_class(self, model):
        mapping = settings.DJANGOSOLR_FIELD_MAPPING
        if model._meta.model:
            for df in model._meta.model._meta.local_fields:
                kwargs = dict(name=df.name, stored=True, indexed=True, multivalued=False, primary_key=df.primary_key)
                sc = df.__class__.__module__ + '.' + df.__class__.__name__
                f_module, f_classname = mapping[sc].rsplit('.', 1)
                f = getattr(import_module(f_module), f_classname)(**kwargs) 
                model._add_to_class(f.name, f)

Example 9

Project: django-primate
Source File: models.py
View license
def register_user_model():
    from django.conf import settings
    if not getattr(settings, 'AUTH_USER_MODEL', False):
        raise SiteUserNotAvailable(
            'You need to set AUTH_USER_MODEL in your project settings'
        )
    try:
        mod_name, cls_name = settings.AUTH_USER_MODEL.rsplit('.', 1)
        mod = import_module(mod_name)
    except ImportError, e:
        raise SiteUserNotAvailable(e)
    try:
        getattr(mod, cls_name)
    except AttributeError, e:
        raise SiteUserNotAvailable(e)

Example 10

Project: django-formwizard
Source File: __init__.py
View license
def get_storage(path, *args, **kwargs):
    i = path.rfind('.')
    module, attr = path[:i], path[i+1:]
    try:
        mod = import_module(module)
    except ImportError, e:
        raise MissingStorageModule(
            'Error loading storage %s: "%s"' % (module, e))
    try:
        storage_class = getattr(mod, attr)
    except AttributeError:
        raise MissingStorageClass(
            'Module "%s" does not define a storage named "%s"' % (module, attr))
    return storage_class(*args, **kwargs)

Example 11

Project: django-mediasync
Source File: __init__.py
View license
def load_backend(backend_name):
    try:
        backend = import_module(backend_name)
        return backend.Client()
    except ImportError, e:
        raise ImproperlyConfigured(("%s is not a valid mediasync backend. \n" +
            "Error was: %s") % (backend_name, e))

Example 12

Project: django-batch-requests
Source File: settings.py
View license
def import_class(class_path):
    '''
        Imports the class for the given class name.
    '''
    module_name, class_name = class_path.rsplit(".", 1)
    module = import_module(module_name)
    claz = getattr(module, class_name)
    return claz

Example 13

Project: django-permissionsx
Source File: utils.py
View license
def get_class(module_name, cls_name):
    try:
        module = importlib.import_module(module_name)
    except ImportError:
        raise ImportError('Cannot import class "{0}"'.format('.'.join((module_name, cls_name))))
    try:
        cls = getattr(module, cls_name)
    except AttributeError:
        raise ImportError('Class "{0}" not found in {1}'.format(cls_name, module_name))
    else:
        return cls

Example 14

Project: dj-webmachine
Source File: __init__.py
View license
def autodiscover():
    """
    Auto-discover INSTALLED_APPS resource.py modules and fail silently when
    not present. This forces an import on them to register any resource bits they
    may want.
    """

    from django.conf import settings
    from django.utils.importlib import import_module
    from django.utils.module_loading import module_has_submodule

    for app in settings.INSTALLED_APPS:
        mod = import_module(app)
        # Attempt to import the app's resource module.
        try:
            import_module('%s.resources' % app)
        except:
            if module_has_submodule(mod, 'resources'):
                raise 

Example 15

View license
def get_serializer(serializer):
    """ Load a serializer. """
    if isinstance(serializer, string_types):
        try:
            app_label, serializer_name = serializer.split('.')
            app_package = get_application(app_label)
            serializer_module = import_module('%s.serializers' % app_package)
            serializer = getattr(serializer_module, serializer_name)
        except Exception:
            logger.error('Serializer %s not found' % serializer)
            return None

    return serializer

Example 16

Project: dynamic-models
Source File: utils.py
View license
def reregister_in_admin(admin_site, model, admin_class=None):
    " (re)registers a dynamic model in the given admin site "

    # We use our own unregister, to ensure that the correct
    # existing model is found 
    # (Django's unregister doesn't expect the model class to change)
    unregister_from_admin(admin_site, model)
    admin_site.register(model, admin_class)

    # Reload the URL conf and clear the URL cache
    # It's important to use the same string as ROOT_URLCONF
    reload(import_module(settings.ROOT_URLCONF))
    clear_url_caches()

Example 17

Project: PiplMesh
Source File: panels_pool.py
View license
    def discover_panels(self):
        if self.discovered:
            return
        self.discovered = True

        for app in settings.INSTALLED_APPS:
            try:
                importlib.import_module('.panel', app)
            except ImportError, e:
                message = str(e)
                if message != 'No module named panel':
                    raise

Example 18

Project: djangoembed
Source File: utils.py
View license
def load_class(path):
    """
    dynamically load a class given a string of the format
    
    package.Class
    """
    package, klass = path.rsplit('.', 1)
    module = import_module(package)
    return getattr(module, klass)

Example 19

Project: djangolint
Source File: loader.py
View license
def load_analyzer(analyzer_name):
    module_name, attr = analyzer_name.rsplit('.', 1)
    try:
        module = import_module(module_name)
    except ImportError, e:
        raise ImproperlyConfigured(
            'Error importing analyzer %s: "%s"' % (analyzer_name, e))
    try:
        analyzer = getattr(module, attr)
    except AttributeError, e:
        raise ImproperlyConfigured(
            'Error importing analyzer %s: "%s"' % (analyzer_name, e))
    return analyzer

Example 20

View license
    def setUp(self):
        classify = Classification.objects.create(c_name='test')
        self.art = Article.objects.create(caption='article',
                                          sub_caption='sub_article',
                                          classification=classify,
                                          content='article test',
                                          publish=True)
        settings.SESSION_ENGINE = 'django.contrib.sessions.backends.file'
        engine = import_module(settings.SESSION_ENGINE)
        store = engine.SessionStore()
        store.save()
        self.session = store
        self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key

Example 21

Project: django-failover
Source File: monitor.py
View license
def register():
    """Registers the service classes defined in settings.
    """
    for path in settings.SERVICES:
        try:
            module, classname = path.rsplit('.', 1)
        except ValueError:
            raise ImproperlyConfigured('%s isn\'t a failover service class' % path)
        try:
            mod = import_module(module)
        except ImportError, e:
            raise ImproperlyConfigured('Error importing failover service module %s: "%s"' % (module, e))
        try:
            service_class = getattr(mod, classname)
        except AttributeError:
            raise ImproperlyConfigured('Failover service module "%s" does not define a "%s" class' % (module, classname))
        if not issubclass(service_class, Service):
            raise ImproperlyConfigured('Failover service class "%s" does not inherit from failover.services.base.Service' % classname)
        ServiceMonitor.register(service_class)

Example 22

Project: django-stories
Source File: utils.py
View license
def load_widget(path):
    """Utily to import a custom widget module"""

    if not path:
        return

    index = path.rfind('.')
    module, attr = path[:index], path[index + 1:]

    try:
        mod = import_module(module)
        return getattr(mod, attr)
    except (ImportError, ValueError, AttributeError), e:
        raise ImproperlyConfigured(
            'Error importing widget {0}: "{1}"'.format(path, e))

Example 23

Project: collab
Source File: settings_helper.py
View license
def load_app_middlewares(middleware_classes):
    for app in INSTALLED_APPS:
        try:
            mod = import_module('%s.%s' % (app, 'settings'))
            middleware_classes += mod.MIDDLEWARE_CLASSES
        except:
            continue
    return middleware_classes

Example 24

Project: django-soap-server
Source File: wsgi.py
View license
def load_application(application):
    if isinstance(application, basestring):
        app_module, app_name = application.rsplit('.', 1)
        application = getattr(import_module(app_module), app_name)
    if not callable(application):
        raise ImproperlyConfigured('%s isn\'t callable' % application)
    return application

Example 25

Project: cmdbac
Source File: utils.py
View license
def load_path_attr(path):
    i = path.rfind(".")
    module, attr = path[:i], path[i + 1:]
    try:
        mod = import_module(module)
    except ImportError as e:
        raise ImproperlyConfigured("Error importing %s: '%s'" % (module, e))
    try:
        attr = getattr(mod, attr)
    except AttributeError:
        raise ImproperlyConfigured("Module '%s' does not define a '%s'" % (module, attr))
    return attr

Example 26

Project: django-cacheback
Source File: utils.py
View license
def get_job_class(klass_str):
    """
    Return the job class
    """
    mod_name, klass_name = klass_str.rsplit('.', 1)
    try:
        mod = importlib.import_module(mod_name)
    except ImportError as e:
        logger.error("Error importing job module %s: '%s'", mod_name, e)
        return
    try:
        klass = getattr(mod, klass_name)
    except AttributeError:
        logger.error("Module '%s' does not define a '%s' class", mod_name, klass_name)
        return
    return klass

Example 27

Project: django-wysihtml5
Source File: utils.py
View license
def get_function(function_path):
    """
    import and return function from ``path.to.module.function`` argument
    """
    try:
        mod_name, func_name = function_path.rsplit('.', 1)
        mod = import_module(mod_name)
    except ImportError as e:
        raise ImproperlyConfigured(('Error importing module %s: "%s"' %
                                   (mod_name, e)))
    return getattr(mod, func_name)

Example 28

Project: django-mailviews
Source File: previews.py
View license
def autodiscover():
    """
    Imports all available previews classes.
    """
    from django.conf import settings
    for application in settings.INSTALLED_APPS:
        module = import_module(application)

        if module_has_submodule(module, 'emails'):
            emails = import_module('%s.emails' % application)
            try:
                import_module('%s.emails.previews' % application)
            except ImportError:
                # Only raise the exception if this module contains previews and
                # there was a problem importing them. (An emails module that
                # does not contain previews is not an error.)
                if module_has_submodule(emails, 'previews'):
                    raise

Example 29

Project: django-admin-tools
Source File: utils.py
View license
def _get_dashboard_cls(dashboard_cls, context):
    if isinstance(dashboard_cls, dict):
        curr_url = context.get('request').path
        for key in dashboard_cls:
            admin_site_mod, admin_site_inst = key.rsplit('.', 1)
            admin_site_mod = import_module(admin_site_mod)
            admin_site = getattr(admin_site_mod, admin_site_inst)
            admin_url = reverse('%s:index' % admin_site.name)
            if curr_url.startswith(admin_url):
                mod, inst = dashboard_cls[key].rsplit('.', 1)
                mod = import_module(mod)
                return getattr(mod, inst)
    else:
        mod, inst = dashboard_cls.rsplit('.', 1)
        mod = import_module(mod)
        return getattr(mod, inst)
    raise ValueError('Dashboard matching "%s" not found' % dashboard_cls)

Example 30

Project: django-dbindexer
Source File: base.py
View license
    def compiler(self, compiler_name):
        if compiler_name not in self._dbindexer_cache:
            target = super(DatabaseOperations, self).compiler(compiler_name)
            base = getattr(
                import_module(self.dbindexer_compiler_module), compiler_name)
            class Compiler(base, target):
                pass
            self._dbindexer_cache[compiler_name] = Compiler
        return self._dbindexer_cache[compiler_name]

Example 31

Project: djangoappengine
Source File: views.py
View license
def warmup(request):
    """
    Provides default procedure for handling warmup requests on App
    Engine. Just add this view to your main urls.py.
    """
    for app in settings.INSTALLED_APPS:
        for name in ('urls', 'views', 'models'):
            try:
                import_module('%s.%s' % (app, name))
            except ImportError:
                pass
    content_type = 'text/plain; charset=%s' % settings.DEFAULT_CHARSET
    return HttpResponse("Warmup done.", content_type=content_type)

Example 32

Project: django-webtest
Source File: __init__.py
View license
    @property
    def session(self):
        """
        Obtains the current session variables.
        """
        if 'django.contrib.sessions' in settings.INSTALLED_APPS:
            engine = import_module(settings.SESSION_ENGINE)
            cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None)
            if cookie:
                return engine.SessionStore(cookie)
        return {}

Example 33

Project: django-mongoadmin
Source File: __init__.py
View license
def autodiscover(*args):
    ''' Discover submodules in Django apps that would otherwise be
        ignored (listeners, configforms, etc)

        Usage: autodiscover('configforms'[, 'listeners'[, ...]])
    '''
    from django.conf import settings
    from django.utils.importlib import import_module
    from django.utils.module_loading import module_has_submodule

    for submod in args:
        for app in settings.INSTALLED_APPS:
            mod = import_module(app)
            if module_has_submodule(mod, submod):
                import_module('%s.%s' % (app, submod))

Example 34

Project: ecommerce
Source File: api.py
View license
def get_fulfillment_modules():
    """ Retrieves all fulfillment modules declared in settings. """
    module_paths = getattr(settings, 'FULFILLMENT_MODULES', [])
    modules = []

    for cls_path in module_paths:
        try:
            module_path, _, name = cls_path.rpartition('.')
            module = getattr(importlib.import_module(module_path), name)
            modules.append(module)
        except (ImportError, ValueError, AttributeError):
            logger.exception("Could not load module at [%s]", cls_path)

    return modules

Example 35

Project: django-reminders
Source File: reminders_tags.py
View license
def load_callable(path_to_callable):
    try:
        mod_name, func_name = path_to_callable.rsplit(".", 1)
    except ValueError:
        raise Exception("Improperly configured.")
    try:
        mod = import_module(mod_name)
    except ImportError:
        raise Exception("Could not import %s" % mod_name)
    try:
        func = getattr(mod, func_name)
    except AttributeError:
        raise Exception("The module '%s' does not contain '%s'." % (mod_name, func_name))
    return func

Example 36

Project: idios
Source File: conf.py
View license
def load_path_attr(path):
    i = path.rfind(".")
    module, attr = path[:i], path[i + 1:]
    try:
        mod = importlib.import_module(module)
    except ImportError as e:
        raise ImproperlyConfigured("Error importing {0}: '{1}'".format(module, e))
    try:
        attr = getattr(mod, attr)
    except AttributeError:
        raise ImproperlyConfigured("Module '{0}' does not define a '{1}'".format(module, attr))
    return attr

Example 37

Project: ella
Source File: installedapps.py
View license
def call_modules(auto_discover=()):
    """
    this is called in project urls.py
    for registering desired modules (eg.: admin.py)
    """
    for app in settings.INSTALLED_APPS:
        modules = set(auto_discover)
        if app in INSTALLED_APPS_REGISTER:
            modules.update(INSTALLED_APPS_REGISTER[app])
        for module in modules:
            mod = import_module(app)
            try:
                import_module('%s.%s' % (app, module))
                inst = getattr(mod, '__install__', lambda: None)
                inst()
            except:
                if module_has_submodule(mod, module):
                    raise
    app_modules_loaded.send(sender=None)

Example 38

Project: django-test-utils
Source File: __init__.py
View license
def register_processor(format, processor_module, processors=None):
    """"Register a new processor.

    ``processor_module`` should be the fully qualified module name
    for the processor.

    If ``processors`` is provided, the registration will be added
    to the provided dictionary.

    If ``processors`` is not provided, the registration will be made
    directly into the global register of processors. Adding processors
    directly is not a thread-safe operation.
    """
    module = importlib.import_module(processor_module)
    if processors is None:
        _test_processors[format] = module
    else:
        processors[format] = module

Example 39

Project: pony_barn
Source File: __init__.py
View license
    def register(self, format, module, reg=None):
        """"Register a new router.

        ``module`` should be the fully qualified module name
        for the router.

        If ``reg`` is provided, the registration will be added
        to the provided dictionary.

        If ``reg`` is not provided, the registration will be made
        directly into the global register of reg. Adding reg
        directly is not a thread-safe operation.
        """
        module = importlib.import_module(module)
        if reg is None:
            self._myreg[format] = module
        else:
            reg[format] = module

Example 40

Project: aldryn-search
Source File: utils.py
View license
def get_callable(string_or_callable):
    """
    If given a callable then it returns it, otherwise it resolves the path
    and returns an object.
    """
    if callable(string_or_callable):
        return string_or_callable
    else:
        module_name, object_name = string_or_callable.rsplit('.', 1)
        module = importlib.import_module(module_name)
        return getattr(module, object_name)

Example 41

Project: Arkestra
Source File: modifier_pool.py
View license
    def discover_modifers(self):  
        """
        Looks for adjusters that need to be registered
        """  
        if self.discovered:
            return    
        for app in settings.INSTALLED_APPS:
            try:
                import_module('.plugin_modifiers', app)
            except ImportError:
                pass
        from plugin_modifiers import register
        register()
        self.discovered = True

Example 42

Project: django-money-rates
Source File: settings.py
View license
def import_from_string(val, setting_name):
    """
    Attempt to import a class from a string representation.
    """
    try:
        parts = val.split('.')
        module_path, class_name = '.'.join(parts[:-1]), parts[-1]
        module = importlib.import_module(module_path)
        return getattr(module, class_name)
    except ImportError as e:
        msg = "Could not import '%s' for setting '%s'. %s: %s." % (val, setting_name, e.__class__.__name__, e)
        raise ImportError(msg)

Example 43

Project: django-oauth-toolkit
Source File: settings.py
View license
def import_from_string(val, setting_name):
    """
    Attempt to import a class from a string representation.
    """
    try:
        parts = val.split('.')
        module_path, class_name = '.'.join(parts[:-1]), parts[-1]
        module = importlib.import_module(module_path)
        return getattr(module, class_name)
    except ImportError as e:
        msg = "Could not import '%s' for setting '%s'. %s: %s." % (val, setting_name, e.__class__.__name__, e)
        raise ImportError(msg)

Example 44

View license
def eval_func(func_path, request):
    try:
        module_str = '.'.join(func_path.split('.')[:-1])
        func_str = func_path.split('.')[-1:][0]
        module = import_module(module_str)
        result = getattr(module, func_str)
        if callable(result):
            args, varargs, keywords, defaults = inspect.getargspec(result)
            if 'request' in args:
                result = result(request)
            else:
                result = result()
        return result
    except:
        return func_path

Example 45

Project: django-dashvisor
Source File: __init__.py
View license
def get_backend():
    backend_path = getattr(settings, 'DASHVISOR_BACKEND', 'dashvisor.backends.file.Backend').split('.')
    module_name = ".".join(backend_path[:-1])
    class_name = backend_path[-1]
    backend_module = import_module(module_name)
    return getattr(backend_module, class_name)()

Example 46

Project: django-socialregistration
Source File: mixins.py
View license
    def import_attribute(self, path):
        """
        Import an attribute from a module.
        """
        module = '.'.join(path.split('.')[:-1])
        function = path.split('.')[-1]

        module = importlib.import_module(module)
        return getattr(module, function)

Example 47

Project: tinned-django
Source File: settings.py
View license
def get_local_settings():
    """ localSettings per developer

        For instance, for USER=prophet we will try to use
        mixin ``Prophet`` in CBS Live.
        If it is not present, no problem, exceptions is silenced.
    """
    try:
        developer_settings_name = os.environ.get('USER', '').title()
        live_settings = import_module('{{ project_name }}.live_settings')
        return getattr(live_settings, developer_settings_name)
    except (ImportError, AttributeError):
        class LocalSettings:
            pass
        return LocalSettings

Example 48

Project: sentry
Source File: cases.py
View license
    @before
    def setup_session(self):
        engine = import_module(settings.SESSION_ENGINE)

        session = engine.SessionStore()
        session.save()

        self.session = session

Example 49

Project: gnowsys-studio
Source File: __init__.py
View license
def get_spam_checker(backend_path):
    """Return the selected spam checker backend"""
    try:
        backend_module = import_module(backend_path)
        backend = getattr(backend_module, 'backend')
    except (ImportError, AttributeError):
        warnings.warn('%s backend cannot be imported' % backend_path,
                      RuntimeWarning)
        backend = None
    except ImproperlyConfigured, e:
        warnings.warn(str(e), RuntimeWarning)
        backend = None

    return backend

Example 50

Project: synnefo
Source File: link_static.py
View license
    def collect_files(self, target):
        symlinks = []
        for module, ns in STATIC_FILES.iteritems():
            module = import_module(module)
            static_root = os.path.join(os.path.dirname(module.__file__),
                                       'static')

            # no nested dir exists for the app
            if ns == '':
                for f in os.listdir(static_root):
                    symlinks.append((os.path.join(static_root, f),
                                     os.path.join(target, ns, f)))

            # symlink whole app directory
            else:
                symlinks.append((os.path.join(static_root),
                                 os.path.join(target, ns)))

        return symlinks