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.
147 Examples
3
Example 1
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)
3
Example 2
Project: gnowsys-studio Source File: __init__.py
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
3
Example 3
Project: collab Source File: settings_helper.py
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
3
Example 4
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
3
Example 5
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
3
Example 6
Project: djangolint Source File: loader.py
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
3
Example 7
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)()
3
Example 8
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))
3
Example 9
def __init__(self, site, *args, **kwargs):
"""
Returns a static file storage if available in the given site.
"""
# site is the actual site module
self.site_module = site
if not site == "":
mod = import_module(self.site_module)
mod_path = os.path.dirname(mod.__file__)
location = os.path.join(mod_path, self.source_dir)
super(SiteStaticStorage, self).__init__(location, *args, **kwargs)
else:
super(SiteStaticStorage, self).__init__(*args, **kwargs)
3
Example 10
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
3
Example 11
Project: ecommerce Source File: api.py
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
3
Example 12
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]
3
Example 13
Project: PiplMesh Source File: panels_pool.py
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
3
Example 14
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
3
Example 15
Project: django-primate Source File: models.py
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)
3
Example 16
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)
3
Example 17
Project: django-failover Source File: monitor.py
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)
3
Example 18
Project: tinned-django Source File: settings.py
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
3
Example 19
Project: django-scaffolding Source File: __init__.py
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)]
3
Example 20
Project: django-sitemetrics Source File: providers.py
def get_custom_providers():
"""Imports providers classes by paths given in SITEMETRICS_PROVIDERS setting."""
providers = getattr(settings, 'SITEMETRICS_PROVIDERS', False)
if not providers:
return None
p_clss = []
for provider_path in providers:
path_splitted = provider_path.split('.')
mod = import_module('.'.join(path_splitted[:-1]))
p_cls = getattr(mod, path_splitted[-1])
p_clss.append(p_cls)
return p_clss
3
Example 21
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
3
Example 22
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)
3
Example 23
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])
3
Example 24
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)
3
Example 25
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
3
Example 26
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))
3
Example 27
Project: djangoappengine Source File: views.py
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)
3
Example 28
Project: dynamic-models Source File: utils.py
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()
3
Example 29
Project: django-reminders Source File: reminders_tags.py
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
3
Example 30
Project: django-solr Source File: options.py
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)
3
Example 31
Project: ella Source File: installedapps.py
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)
3
Example 32
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)
3
Example 33
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
3
Example 34
Project: django-nosqladmin Source File: mixins.py
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
3
Example 35
Project: Arkestra Source File: modifier_pool.py
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
3
Example 36
Project: django-angularjs-blog Source File: test_view_blog.py
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
3
Example 37
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
3
Example 38
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)
3
Example 39
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)
3
Example 40
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))
3
Example 41
@before
def setup_session(self):
engine = import_module(settings.SESSION_ENGINE)
session = engine.SessionStore()
session.save()
self.session = session
3
Example 42
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
3
Example 43
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
3
Example 44
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
3
Example 45
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
3
Example 46
Project: django-static Source File: django_static.py
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
3
Example 47
@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))
3
Example 48
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))
3
Example 49
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
3
Example 50
@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 {}