def ready(self): # if ready was already called if hasattr(self, 'bmf_config'): # pragma: no cover return True self.bmf_config = apps.get_app_config(self.bmf_label) if not hasattr(self.bmf_config, 'site'): # pragma: no cover raise ImproperlyConfigured( "Can not find a site attribute in %(cls)s. " "Please import the BMF-Framework before you " "import any BMF-Modules in your INSTALLED_APPS." % { 'cls': self.bmf_config.__class__.__name__ } ) # autodiscover bmf modules ============================================ if module_has_submodule(self.module, "bmf_module"): # pragma: no branch # load instructions of bmf_module.py import_module('%s.%s' % (self.name, "bmf_module")) # see if model needs a number_cycle for model in [m for m in self.models.values() if hasattr(m, '_bmfmeta') and m._bmfmeta.number_cycle]: self.bmf_config.site.register_numbercycle(model) logger.debug('App "%s" (%s) is ready' % ( self.verbose_name, self.label, ))
def autodiscover(self, module_name=None, verbose=True): """Autodiscovers consent classes in the consents.py file of any INSTALLED_APP. """ module_name = module_name or 'consents' writer = sys.stdout.write if verbose else lambda x: x style = color_style() writer(f' * checking for site {module_name} ...\n') for app in django_apps.app_configs: writer(f' * searching {app} \r') try: mod = import_module(app) try: before_import_registry = deepcopy(site_consents.registry) import_module(f'{app}.{module_name}') writer( f' * registered consents \'{module_name}\' from \'{app}\'\n') except ConsentError as e: writer(f' - loading {app}.consents ... ') writer(style.ERROR(f'ERROR! {e}\n')) except ImportError as e: site_consents.registry = before_import_registry if module_has_submodule(mod, module_name): raise SiteConsentError(str(e)) except ImportError: pass
def find_templates(): template_classes.clear() layout_classes.clear() for app in apps.get_app_configs(): if os.path.isfile(os.path.join(app.path, 'mails.py')): import_module('{}.mails'.format(app.name)) for cls in all_template_classes: if cls.abstract: continue found = False for app in apps.get_app_configs(): if in_module(cls, app.module): found = True break if found: template_classes.append(cls) for cls in all_layout_classes: if cls.abstract: continue found = False for app in apps.get_app_configs(): if in_module(cls, app.module): found = True break if found: layout_classes.append(cls)
def autodiscover(self, module_name=None, verbose=True): """Autodiscovers query rule classes in the data_manager.py file of any INSTALLED_APP. """ module_name = module_name or "data_manager" writer = sys.stdout.write if verbose else lambda x: x style = color_style() writer(f" * checking for data manager {module_name} ...\n") for app in django_apps.app_configs: writer(f" * searching {app} \r") try: mod = import_module(app) try: before_import_registry = deepcopy(site_data_manager.registry) import_module(f"{app}.{module_name}") writer(f" * registered '{module_name}' from '{app}'\n") except SiteDataManagerError as e: writer(f" - loading {app}.{module_name} ... ") writer(style.ERROR(f"ERROR! {e}\n")) except ImportError as e: site_data_manager.registry = before_import_registry if module_has_submodule(mod, module_name): raise SiteDataManagerError(str(e)) except ImportError: pass
def import_app_module(app_name, module_name): """Returns a module from a given app by its name. :param str app_name: :param str module_name: :rtype: module or None """ name_split = app_name.split('.') if name_split[-1][0].isupper(): # Seems that we have app config class path here. app_name = '.'.join(name_split[:-2]) module = import_module(app_name) try: sub_module = import_module('%s.%s' % (app_name, module_name)) return sub_module except: # The same bubbling strategy as in autodiscover_modules(). if module_has_submodule(module, module_name): # Module is in a package. raise return None
def handle(self, *args, **options): fixture = options['fixture'] format = options['format'] indent = options['indent'] available_fixtures = {} for app in settings.INSTALLED_APPS: try: fixture_gen = import_module(".fixture_gen", app) except ImportError: if module_has_submodule(import_module(app), "fixture_gen"): raise continue for obj in fixture_gen.__dict__.values(): if getattr(obj, "__fixture_gen__", False): available_fixtures[(app.rsplit(".", 1)[-1], obj.__name__)] = obj app_label, fixture_name = fixture.rsplit(".", 1) try: fixture = available_fixtures[(app_label, fixture_name)] except KeyError: available = ", ".join( "%s.%s" % (app_label, fixture_name) for app_label, fixture_name in available_fixtures) raise CommandError("Fixture generator '%s' not found, available " "choices: %s" % (fixture, available)) requirements, models = linearize_requirements(available_fixtures, fixture) settings.DATABASES[FIXTURE_DATABASE] = { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", } old_routers = router.routers router.routers = [FixtureRouter(models)] try: call_command("migrate", database=FIXTURE_DATABASE, verbosity=0, interactive=False) for fixture_func in requirements: fixture_func() call_command( "dumpdata", *[ "%s.%s" % (m._meta.app_label, m._meta.object_name) for m in models ], **dict(format=format, indent=indent, verbosity=0, database=FIXTURE_DATABASE)) finally: del settings.DATABASES[FIXTURE_DATABASE] if isinstance(connections._connections, dict): del connections._connections[FIXTURE_DATABASE] else: delattr(connections._connections, FIXTURE_DATABASE) router.routers = old_routers
def autodiscover(self, module_name=None, apps=None, verbose=None): """Autodiscovers classes in the visit_schedules.py file of any INSTALLED_APP. """ self.loaded = True module_name = module_name or "visit_schedules" verbose = True if verbose is None else verbose if verbose: sys.stdout.write( f" * checking site for module '{module_name}' ...\n") for app in apps or django_apps.app_configs: try: mod = import_module(app) try: before_import_registry = copy.copy( site_visit_schedules._registry) import_module(f"{app}.{module_name}") if verbose: sys.stdout.write(" * registered visit schedule from " f"'{app}'\n") except Exception as e: if f"No module named '{app}.{module_name}'" not in str(e): raise site_visit_schedules._registry = before_import_registry if module_has_submodule(mod, module_name): raise except ModuleNotFoundError: pass
def import_app_module(app_name: str, module_name: str) -> Optional[ModuleType]: """Returns a module from a given app by its name. :param app_name: :param module_name: """ name_split = app_name.split('.') if name_split[-1][0].isupper( ): # Seems that we have app config class path here. app_name = '.'.join(name_split[:-2]) module = import_module(app_name) try: sub_module = import_module(f'{app_name}.{module_name}') return sub_module except: # The same bubbling strategy as in autodiscover_modules(). if module_has_submodule(module, module_name): # Module is in a package. raise return None
def autodiscover(): """ Auto-discover INSTALLED_APPS sockets.py modules and fail silently when not present. NOTE: socketio_autodiscover was inspired/copied from django.contrib.admin autodiscover """ global LOADING_SOCKETIO if LOADING_SOCKETIO: return LOADING_SOCKETIO = True import imp from django.conf import settings for app in settings.INSTALLED_APPS: try: app_path = import_module(app).__path__ except AttributeError: continue try: imp.find_module('sockets', app_path) except ImportError: continue import_module("%s.sockets" % app) LOADING_SOCKETIO = False
def autodiscover(self, module_name=None): """Autodiscovers classes in the surveys.py file of any INSTALLED_APP. """ module_name = module_name or 'surveys' sys.stdout.write(' * checking for site {} ...\n'.format(module_name)) for app in django_apps.app_configs: try: mod = import_module(app) try: before_import_registry = copy.copy(site_surveys._registry) import_module('{}.{}'.format(app, module_name)) sys.stdout.write(' * registered surveys from application ' '\'{}\'\n'.format(app)) except (SiteSurveysError, SiteSurveysAlreadyRegistered, SiteSurveysError, AddSurveyDateError, AddSurveyMapAreaError, AddSurveyNameError, AddSurveyOverlapError): raise except Exception as e: if 'No module named \'{}.{}\''.format( app, module_name) not in str(e): raise Exception(e) site_surveys._registry = before_import_registry if module_has_submodule(mod, module_name): raise except ImportError: pass
def autodiscover(): """ Auto-discover INSTALLED_APPS sockets.py modules and fail silently when not present. NOTE: socketio_autodiscover was inspired/copied from django.contrib.admin autodiscover """ global LOADING_SOCKETIO if LOADING_SOCKETIO: return LOADING_SOCKETIO = True import imp from django.conf import settings for app in settings.INSTALLED_APPS: try: app_path = import_module(app).__path__ except AttributeError: continue except ImportError: continue try: imp.find_module('sockets', app_path) except ImportError: continue import_module("%s.sockets" % app) LOADING_SOCKETIO = False
def autodiscover(self, module_name=None): """Autodiscovers rules in the metadata_rules.py file of any INSTALLED_APP. """ module_name = module_name or "metadata_rules" sys.stdout.write(f" * checking for {module_name} ...\n") for app in django_apps.app_configs: try: mod = import_module(app) try: before_import_registry = copy.copy( site_metadata_rules.registry) import_module(f"{app}.{module_name}") except Exception as e: if f"No module named '{app}.{module_name}'" not in str(e): site_metadata_rules.registry = before_import_registry if module_has_submodule(mod, module_name): raise else: sys.stdout.write( f" - imported metadata rules from '{app}.{module_name}'\n" ) except ImportError: pass
def autodiscover(): """ Auto-discover INSTALLED_APPS backbone_api.py modules. """ # This code is based off django.contrib.admin.__init__ from django.conf import settings try: # Django versions >= 1.9 from django.utils.module_loading import import_module except ImportError: # Django versions < 1.9 from django.utils.importlib import import_module from django.utils.module_loading import module_has_submodule from backbone.views import BackboneAPIView # This is to prevent a circular import issue for app in settings.INSTALLED_APPS: mod = import_module(app) # Attempt to import the app's backbone module. try: import_module('%s.backbone_api' % app) except: # Decide whether to bubble up this error. If the app just # doesn't have an backbone module, we can ignore the error # attempting to import it, otherwise we want it to bubble up. if module_has_submodule(mod, 'backbone_api'): raise
def autodiscover(module_name=None, verbose=False): """Autodiscovers classes in the notifications.py file of any INSTALLED_APP. """ module_name = module_name or "notifications" verbose = True if verbose is None else verbose sys.stdout.write(f" * checking for {module_name} ...\n") for app in django_apps.app_configs: before_import_registry = None try: mod = import_module(app) try: before_import_registry = copy.copy(site_notifications._registry) import_module(f"{app}.{module_name}") if verbose: sys.stdout.write( f" * registered notifications from application '{app}'\n" ) except Exception as e: if f"No module named '{app}.{module_name}'" not in str(e): site_notifications._registry = before_import_registry if module_has_submodule(mod, module_name): raise except ModuleNotFoundError: pass
def ready(self): # if ready was already called if hasattr(self, 'bmf_config'): # pragma: no cover return True self.bmf_config = apps.get_app_config(self.bmf_label) if not hasattr(self.bmf_config, 'site'): # pragma: no cover raise ImproperlyConfigured( "Can not find a site attribute in %(cls)s. " "Please import the BMF-Framework before you " "import any BMF-Modules in your INSTALLED_APPS." % {'cls': self.bmf_config.__class__.__name__}) # autodiscover bmf modules ============================================ if module_has_submodule(self.module, "bmf_module"): # pragma: no branch # load instructions of bmf_module.py import_module('%s.%s' % (self.name, "bmf_module")) # # see if model needs a number_cycle # for model in [m for m in self.models.values() if hasattr(m, '_bmfmeta') and m._bmfmeta.number_cycle]: # self.bmf_config.site.register_numbercycle(model) logger.debug('App "%s" (%s) is ready' % ( self.verbose_name, self.label, ))
def autodiscover(): """ Auto-discover INSTALLED_APPS report.py modules and fail silently when not present. Borrowed form django.contrib.admin """ # from django.utils.importlib import import_module # from importlib import import_module from django.utils.module_loading import import_module from django.utils.module_loading import module_has_submodule global reports for app in settings.INSTALLED_APPS: mod = import_module(app) before_import_registry = None # Attempt to import the app's admin module. try: before_import_registry = copy.copy(reports) import_module('%s.reports' % app) except: # Reset the model registry to the state before the last import as # this import will have to reoccur on the next request and this # could raise NotRegistered and AlreadyRegistered exceptions # (see #8245). reports = before_import_registry # Decide whether to bubble up this error. If the app just # doesn't have an admin module, we can ignore the error # attempting to import it, otherwise we want it to bubble up. if module_has_submodule(mod, 'reports'): raise
def autodiscover(): """ Auto-discover INSTALLED_APPS admin.py modules and fail silently when not present. This forces an import on them to register any admin bits they may want. """ from django.conf import settings from django.utils.module_loading import module_has_submodule, import_module setattr(settings, 'CRISPY_TEMPLATE_PACK', 'bootstrap3') setattr( settings, 'CRISPY_CLASS_CONVERTERS', { "textinput": "textinput textInput form-control", "fileinput": "fileinput fileUpload form-control", "passwordinput": "textinput textInput form-control", }) from xadmin.views import register_builtin_views register_builtin_views(site) # load xadmin settings from XADMIN_CONF module try: xadmin_conf = getattr(settings, 'XADMIN_CONF', 'xadmin_conf.py') conf_mod = import_module(xadmin_conf) except Exception: conf_mod = None if conf_mod: for key in dir(conf_mod): setting = getattr(conf_mod, key) try: if issubclass(setting, Settings): site.register_settings(setting.__name__, setting) except Exception: pass from xadmin.plugins import register_builtin_plugins register_builtin_plugins(site) from django.apps import apps for app_config in apps.get_app_configs(): # Attempt to import the app's admin module. try: before_import_registry = site.copy_registry() import_module('%s.adminx' % app_config.name) except: # Reset the model registry to the state before the last import as # this import will have to reoccur on the next request and this # could raise NotRegistered and AlreadyRegistered exceptions # (see #8245). site.restore_registry(before_import_registry) # Decide whether to bubble up this error. If the app just # doesn't have an admin module, we can ignore the error # attempting to import it, otherwise we want it to bubble up. if module_has_submodule(app_config.module, 'adminx'): raise
def autodiscover(): for app in settings.INSTALLED_APPS: mod = import_module(app) try: import_module('%s.%s' % (app, 'link_resolvers')) except: if module_has_submodule(mod, 'link_resolvers'): raise
def autodiscover(): """ Auto-discover INSTALLED_APPS admin.py modules and fail silently when not present. This forces an import on them to register any admin bits they may want. """ from django.conf import settings from django.utils.module_loading import module_has_submodule, import_module setattr(settings, 'CRISPY_TEMPLATE_PACK', 'bootstrap3') setattr(settings, 'CRISPY_CLASS_CONVERTERS', { "textinput": "textinput textInput form-control", "fileinput": "fileinput fileUpload form-control", "passwordinput": "textinput textInput form-control", }) from xadmin.views import register_builtin_views register_builtin_views(site) # load xadmin settings from XADMIN_CONF module try: xadmin_conf = getattr(settings, 'XADMIN_CONF', 'xadmin_conf.py') conf_mod = import_module(xadmin_conf) except Exception: conf_mod = None if conf_mod: for key in dir(conf_mod): setting = getattr(conf_mod, key) try: if issubclass(setting, Settings): site.register_settings(setting.__name__, setting) except Exception: pass from xadmin.plugins import register_builtin_plugins register_builtin_plugins(site) from django.apps import apps for app_config in apps.get_app_configs(): # Attempt to import the app's admin module. try: before_import_registry = site.copy_registry() import_module('%s.adminx' % app_config.name) except: # Reset the model registry to the state before the last import as # this import will have to reoccur on the next request and this # could raise NotRegistered and AlreadyRegistered exceptions # (see #8245). site.restore_registry(before_import_registry) # Decide whether to bubble up this error. If the app just # doesn't have an admin module, we can ignore the error # attempting to import it, otherwise we want it to bubble up. if module_has_submodule(app_config.module, 'adminx'): raise
def ready(self): """Perform any project-wide initialization.""" for app in apps.get_app_configs(): # Import all serializers modules to ensure API serialization code # is initialized (i.e. all defined serializers are registered). try: import_module('{}.serializers'.format(app.name)) except ModuleNotFoundError: pass
def autoload(submodules): for app in settings.INSTALLED_APPS: mod = import_module(app) for submodule in submodules: try: import_module("{0}.{1}".format(app, submodule)) except: if module_has_submodule(mod, submodule): raise
def get_url_patterns(): res = _init_url_patterns() for appname in settings.INSTALLED_APPS: appmodule = import_module(appname) is_lucterios_ext = False for _, modname, ispkg in pkgutil.iter_modules(appmodule.__path__): if (modname[:5] == 'views') and not ispkg: view = import_module(appname + '.' + modname) for obj in inspect.getmembers(view): try: if obj[1].url_text != '': if inspect.isclass(obj[1]): is_lucterios_ext = True as_view_meth = getattr(obj[1], "as_view") res.append( url(r"^%s$" % obj[1].url_text, as_view_meth())) except AttributeError: pass elif settings.APPLIS_MODULE == appmodule: is_lucterios_ext = True if not is_lucterios_ext: try: patterns = getattr(import_module('%s.urls' % appname), 'urlpatterns', None) if isinstance(patterns, (list, tuple)): for url_pattern in patterns: module_items = appname.split('.') if module_items[0] == 'lucterios': continue if module_items[0] == 'django': res.append(url_pattern) else: res.append( url( r"^%s/%s" % (module_items[-1], url_pattern.pattern._regex[1:]), url_pattern.callback, None, url_pattern.pattern.name)) except ImportError: pass print("PluginManager.get_instance") for plugin_item in PluginManager.get_instance(): for view_item in plugin_item.views: res.append(url(r"^%s$" % view_item.url_text, view_item.as_view())) try: from django.contrib.admin.sites import site res.append(url(r'^accounts/login/$', site.login)) except ImportError: pass res.extend(staticfiles_urlpatterns()) logging.getLogger('lucterios.core.init').debug("Urls:" + '\n'.join( str(res_item) for res_item in res)) Signal.call_signal("auditlog_register") LucteriosAuditlogModelRegistry.main_enabled() return res
def import_handlers_module(app_module_name): handlers_module_name = '%s.handlers' % app_module_name try: import_module(handlers_module_name) except ImportError: # we need to re-raise exception in case there was import errors inside # handlers.py module handlers_file_name = get_handlers_file_name(app_module_name) if os.path.exists(handlers_file_name): raise
def find_commands(app): """Return a dict of `command_name: command_obj` for the given app.""" commands = {} app_module = import_module(app) # Fail loudly if an app doesn't exist. try: commands_module = import_module(app + '.commands') except ImportError: pass else: for command in vars(commands_module).itervalues(): if isinstance(command, Command): commands[command.name] = command return commands
def ready(self): # if ready was already called if hasattr(self, 'bmf_config'): # pragma: no cover return True self.bmf_config = apps.get_app_config(self.bmf_label) if not hasattr(self.bmf_config, 'site'): # pragma: no cover raise ImproperlyConfigured( "Can not find a site attribute in %(cls)s. " "Please import the BMF-Framework before you " "import any BMF-Modules in your INSTALLED_APPS." % {'cls': self.bmf_config.__class__.__name__}) # autodiscover bmf modules ============================================ if module_has_submodule(self.module, "bmf_module"): # pragma: no branch # load instructions of bmf_module.py import_module('%s.%s' % (self.name, "bmf_module")) # see if model needs a number_cycle for model in [ m for m in self.models.values() if hasattr(m, '_bmfmeta') and m._bmfmeta.number_cycle ]: self.bmf_config.site.register_numbercycle(model) # copy = self.bmfsite.copy() # try: # # get a copy of old site configuration # logger.debug('bmf_module from %s loaded' % app_config.name) # site.register_workspace_views(app_config) # except: # # Reset the model registry to the state before the last import # # skiping this may result in an AlreadyRegistered Error # site.modules = before_import_m # site.currencies = before_import_c # site.settings = before_import_s # site.reports = before_import_p # site.workspace = before_import_w # # # Decide whether to bubble up this error # raise logger.debug('App "%s" (%s) is ready' % ( self.verbose_name, self.label, ))
def get_default_model(cls, module, modelname=None, kind=None): models = [] from django.utils.module_loading import import_module try: dir_pack = dirname(import_module("%s.printmodel" % module).__file__) for _dir, _dirs, filenames in walk(dir_pack): for filename in filenames: if (filename[-3:] == ".py") and not filename.startswith('_'): mod_name = filename[:-3] print_mod = import_module("%s.printmodel.%s" % (module, mod_name)) if ((modelname is None) or (getattr(print_mod, "modelname") == modelname)) and ((kind is None) or (getattr(print_mod, "kind") == kind)): models.append((mod_name, getattr(print_mod, "name"))) except ImportError: pass return models
def get_watched_paths(self, recursive=True): app_paths = [] for config in self.configs: source_dir = os.path.abspath(os.path.dirname(config[0])) app_paths.append( (config[0], source_dir) ) #styl_path = os.path.join(settings.DJANGO_ROOT, 'styl') project_path = self.app_root if os.path.exists(project_path): app_paths.append((project_path, project_path)) for path in settings.STATICFILES_DIRS: #styl_path = os.path.join(path, 'styl') styl_path = path if os.path.exists(styl_path): app_paths.append((styl_path, styl_path)) for appname in settings.INSTALLED_APPS: try: try: app = import_string(appname) except: app = import_module(appname) if inspect.ismodule(app): pass elif inspect.isclass(app): app = import_module(app.name) else: raise Exception #styl_path = os.path.join(os.path.dirname(app.__file__), 'styl') styl_path = os.path.dirname(app.__file__) if os.path.exists(styl_path): app_paths.append((appname, styl_path)) except Exception: self.print_error(u"Failed to import %s (%s)" % (appname, app)) if recursive: for path in app_paths: for path2 in app_paths: if path[1] != path2[1] and path2[1].startswith(path[1]): app_paths.remove(path2) return app_paths
def import_object(name): module, attr = name.rsplit('.', 1) mod = import_module(module) try: return getattr(mod, attr) except AttributeError: raise ImportError("'%s' module has no attribute '%s'" % (module, attr))
def update_admin_urls(): """Admin urls set have to be updated or all new registered models will be shown as disabled in admin area""" # Delete the old admin URLs old_pattern = None admin_regex = r'^admin/' project_urls = import_module(settings.ROOT_URLCONF) for url_item in project_urls.urlpatterns: try: if url_item.app_name == 'admin': old_pattern = url_item admin_regex = url_item.regex.pattern project_urls.urlpatterns.remove(url_item) break except AttributeError: # Bypass the non-admin URLconf logger.error('Error when finding and removing old admin URLconf.') # Reload updated admin URLs try: admin.autodiscover() project_urls.urlpatterns.append( url(admin_regex, include(admin.site.urls)) ) except: logger.error('Error when updating new admin URLconfs.') if old_pattern: project_urls.urlpatterns.append(old_pattern)
def autodiscover(): """Auto-discover INSTALLED_APPS agnocomplete modules.""" module_name = "autocomplete" for app in settings.INSTALLED_APPS: # Attempt to import the app's 'routing' module module = '{}.{}'.format(app, module_name) try: import_module(module) except ImportError as ex: reason = ex.args[0] if 'No module named {}'.format(module_name) in reason \ or "No module named '{}'".format(module) in reason: logger.info('No module named {}'.format(module)) else: # re-raise - something's wrong logger.warning(ex) raise ImportError(ex)
def load(self): try: # Django versions >= 1.9 from django.utils.module_loading import import_module except ImportError: # Django versions < 1.9 from django.utils.importlib import import_module from django.core import exceptions self._plugins = [] for module_path in settings.REQUEST_PLUGINS: try: dot = module_path.rindex('.') except ValueError: raise exceptions.ImproperlyConfigured('%s isn\'t a plugin' % module_path) plugin, plugin_classname = module_path[:dot], module_path[dot + 1:] try: mod = import_module(plugin) except ImportError as e: raise exceptions.ImproperlyConfigured('Error importing plugin %s: "%s"' % (plugin, e)) try: plugin_class = getattr(mod, plugin_classname) except AttributeError: raise exceptions.ImproperlyConfigured('Plugin "%s" does not define a "%s" class' % (plugin, plugin_classname)) self._plugins.append(plugin_class())
def setup_session(self): engine = import_module(settings.SESSION_ENGINE) session = engine.SessionStore() session.save() self.session = session
def register_builtin_plugins(site): from django.utils.module_loading import import_module from django.conf import settings exclude_plugins = getattr(settings, 'XADMIN_EXCLUDE_PLUGINS', []) [import_module('nadmin.plugins.%s' % plugin) for plugin in PLUGINS if plugin not in exclude_plugins]
def get_connection(path=None, fail_silently=False, **kwargs): """ Load an sms backend and return an instance of it. :param string path: backend python path. Default: sendsms.backends.console.SmsBackend :param bool fail_silently: Flag to not throw exceptions on error. Default: False :returns: backend class instance. :rtype: :py:class:`~sendsms.backends.base.BaseSmsBackend` subclass """ path = path or getattr( settings, "SENDSMS_BACKEND", "sendsms.backends.locmem.SmsBackend" ) try: mod_name, klass_name = path.rsplit(".", 1) mod = import_module(mod_name) except AttributeError as e: raise ImproperlyConfigured( u'Error importing sms backend module %s: "%s"' % (mod_name, e) ) try: klass = getattr(mod, klass_name) except AttributeError: raise ImproperlyConfigured( 'Module "%s" does not define a "%s" class' % (mod_name, klass_name) ) return klass(fail_silently=fail_silently, **kwargs)
def import_by_path(dotted_path, error_prefix=''): """ Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImproperlyConfigured if something goes wrong. """ try: module_path, class_name = dotted_path.rsplit('.', 1) except ValueError: raise ImproperlyConfigured("%s%s doesn't look like a module path" % (error_prefix, dotted_path)) try: module = import_module(module_path) except ImportError as e: msg = '%sError importing module %s: "%s"' % (error_prefix, module_path, e) six.reraise(ImproperlyConfigured, ImproperlyConfigured(msg), sys.exc_info()[2]) try: attr = getattr(module, class_name) except AttributeError: raise ImproperlyConfigured( '%sModule "%s" does not define a "%s" attribute/class' % (error_prefix, module_path, class_name)) return attr
def ready(self): try: permissions_model = import_string("APPS.RBAC.models.Permissions") permissions_model.objects.get_or_create(name="管理员权限", codeName="AdminPermission") permissions_dir = os.listdir( os.path.join(BASE_DIR, "Module_Auth", "Permissions")) for permission_py in permissions_dir: if ".py" in permission_py: permission_name = permission_py.split(".py")[0] permissions = import_module( f"Module_Auth.Permissions.{permission_name}") class_members = inspect.getmembers(permissions, inspect.isclass) print(class_members) classes = [(c[0], c[1].__doc__.strip()) for c in class_members if c[0] not in ('MainPermission', 'SecondaryPermission')] prefixes = [('GET', '获取'), ('PUT', '修改'), ('POST', '创建'), ('DELETE', '删除')] for prefix in prefixes: for Permission in classes: permissions_model.objects.get_or_create( name=f"{prefix[1]}{Permission[1]}", codeName=f"{prefix[0]}_{Permission[0]}") print(f"<{prefix[1]}{Permission[1]}> 权限创建成功") print(f"---------------{permission_py} 模块内权限数据创建/检查完毕") except Exception as e: print(f"权限数据未创建,请先进行migrate操作,{e}")
def model_cleanup(self): create_models() importlib.reload(import_module(settings.ROOT_URLCONF)) app_config = apps.get_app_config("django_models_from_csv") hydrate_models_and_permissions(app_config) apps.clear_cache() clear_url_caches()
def get_integration(integration, *args, **kwargs): """Return a integration instance specified by `integration` name""" klass = integration_cache.get(integration, None) if not klass: integration_filename = "%s_integration" % integration integration_module = None for app in settings.INSTALLED_APPS: try: integration_module = import_module(".integrations.%s" % integration_filename, package=app) break except ImportError: pass if not integration_module: raise IntegrationModuleNotFound("Missing integration: %s" % (integration)) integration_class_name = "".join( integration_filename.title().split("_")) try: klass = getattr(integration_module, integration_class_name) except AttributeError: raise IntegrationNotConfigured( "Missing %s class in the integration module." % integration_class_name) integration_cache[integration] = klass return klass(*args, **kwargs)
def pick_backend(): '''Get storefront search function of configured backend :rtype: callable with one argument of type str ''' return import_module(settings.SEARCH_BACKEND).search_storefront
def upgrade(self): self.btnupgrade.config(state=DISABLED) self.instance_list.config(state=DISABLED) try: from logging import getLogger admin_path = import_module( "lucterios.install.lucterios_admin").__file__ proc = Popen( [sys.executable, admin_path, "update"], stderr=STDOUT, stdout=PIPE) value = proc.communicate()[0] try: value = value.decode('ascii') except: pass six.print_(value) if proc.returncode != 0: getLogger("lucterios.admin").error(value) else: getLogger("lucterios.admin").info(value) showinfo(ugettext("Lucterios installer"), ugettext( "The application must restart")) python = sys.executable os.execl(python, python, *sys.argv) finally: self._refresh_modules() self.btnupgrade.config(state=NORMAL) self.instance_list.config(state=NORMAL)
def import_by_path(dotted_path, error_prefix=''): """ Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImproperlyConfigured if something goes wrong. """ try: module_path, class_name = dotted_path.rsplit('.', 1) except ValueError: raise ImproperlyConfigured("%s%s doesn't look like a module path" % (error_prefix, dotted_path)) try: module = import_module(module_path) except ImportError as e: msg = '%sError importing module %s: "%s"' % ( error_prefix, module_path, e) six.reraise(ImproperlyConfigured, ImproperlyConfigured(msg), sys.exc_info()[2]) try: attr = getattr(module, class_name) except AttributeError: raise ImproperlyConfigured( '%sModule "%s" does not define a "%s" attribute/class' % (error_prefix, module_path, class_name)) return attr
def handle(self, **options): if len(settings.SOCKJS_CLASSES) > 1: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured( "Multiple connections not yet supported") module_name, cls_name = settings.SOCKJS_CLASSES[0].rsplit('.', 1) module = import_module(module_name) cls = getattr(module, cls_name) channel = getattr(settings, 'SOCKJS_CHANNEL', '/chat') if not channel.startswith('/'): channel = '/%s' % channel router = SockJSRouter(cls, channel) app_settings = { 'debug': settings.DEBUG, } port = int(options['port']) app = web.Application(router.urls, **app_settings) app.listen(port, no_keep_alive=options['no_keep_alive']) print("Running sock app on port", port, "with channel", channel) try: ioloop.IOLoop.instance().start() except KeyboardInterrupt: pass
def get_watched_paths(self): app_paths = [] for config in self.configs: source_dir = os.path.abspath(os.path.dirname(config[0])) app_paths.append( (config[0], source_dir) ) #styl_path = os.path.join(settings.DJANGO_ROOT, 'styl') styl_path = settings.DJANGO_ROOT if os.path.exists(styl_path): app_paths.append((styl_path, styl_path)) for path in settings.STATICFILES_DIRS: #styl_path = os.path.join(path, 'styl') styl_path = path if os.path.exists(styl_path): app_paths.append((styl_path, styl_path)) for appname in settings.INSTALLED_APPS: app = import_module(appname) #styl_path = os.path.join(os.path.dirname(app.__file__), 'styl') styl_path = os.path.dirname(app.__file__) if os.path.exists(styl_path): app_paths.append((appname, styl_path)) return app_paths
def ready(self): # if ready was already called if hasattr(self, 'bmf_config'): # pragma: no cover return True self.bmf_config = apps.get_app_config(self.bmf_label) if not hasattr(self.bmf_config, 'site'): # pragma: no cover raise ImproperlyConfigured( "Can not find a site attribute in %(cls)s. " "Please import the BMF-Framework before you " "import any BMF-Modules in your INSTALLED_APPS." % { 'cls': self.bmf_config.__class__.__name__ } ) # autodiscover bmf modules ============================================ if module_has_submodule(self.module, "bmf_module"): # pragma: no branch # load instructions of bmf_module.py import_module('%s.%s' % (self.name, "bmf_module")) # see if model needs a number_cycle for model in [m for m in self.models.values() if hasattr(m, '_bmfmeta') and m._bmfmeta.number_cycle]: self.bmf_config.site.register_numbercycle(model) # copy = self.bmfsite.copy() # try: # # get a copy of old site configuration # logger.debug('bmf_module from %s loaded' % app_config.name) # site.register_workspace_views(app_config) # except: # # Reset the model registry to the state before the last import # # skiping this may result in an AlreadyRegistered Error # site.modules = before_import_m # site.currencies = before_import_c # site.settings = before_import_s # site.reports = before_import_p # site.workspace = before_import_w # # # Decide whether to bubble up this error # raise logger.debug('App "%s" (%s) is ready' % ( self.verbose_name, self.label, ))
def _init_django(self): with open(join(self.project_path, '.pydevproject'), 'rb') as flb: xml = etree.fromstring(flb.read()) properties = xml.xpath('pydev_variables_property') if len(properties) != 1: raise GeneratorException("Bad 'pydev' project!") keys = properties[0].xpath('key') values = properties[0].xpath('value') if len(keys) != len(values): raise GeneratorException("Bad 'pydev' project!") for key_idx in range(len(keys)): os.environ.setdefault(keys[key_idx].text, values[key_idx].text) sys.path.append(self.project_path) import django.conf import_module(os.environ[django.conf.ENVIRONMENT_VARIABLE]) reload(django.conf) django.setup()
def can_send_email(xfer): from django.utils.module_loading import import_module from django.apps.registry import apps if apps.is_installed("lucterios.mailing"): fct_mailing_mod = import_module('lucterios.mailing.functions') return fct_mailing_mod.will_mail_send() else: return False
def __init__(self, client): ## workaround for issue: http://code.djangoproject.com/ticket/10899 settings.SESSION_ENGINE = 'django.contrib.sessions.backends.file' engine = import_module(settings.SESSION_ENGINE) store = engine.SessionStore() store.save() self.session = store client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key
def handle_app_config(self, app_config, **options): if app_config.models_module is None: raise CommandError("You must provide an app to generate an API") if django.VERSION[1] == 7: force = options["force"] if "force" in options else False format = options["format"] if "format" in options else None depth = options["depth"] if "depth" in format else 0 if "serializers" in options: serializers = options["serializers"] else: serializers = False views = options["views"] if "views" in options else False urls = options["urls"] if "urls" in options else False template = options["template"] if "template" in options else None elif django.VERSION[1] >= 8: force = options["force"] format = options["format"] depth = options["depth"] serializers = options["serializers"] views = options["views"] urls = options["urls"] template = options["template"] else: raise CommandError("You must be using Django 1.7, 1.8 or 1.9") if template is not None: for submodule, symbols in template_imports.items(): mod = import_module("%s.%s" % (template, submodule)) for s in symbols: setattr(generators_module, s, getattr(mod, s)) if format == "viewset": generator = ViewSetGenerator(app_config, force) elif format == "apiview": generator = APIViewGenerator(app_config, force) elif format == "function": generator = FunctionViewGenerator(app_config, force) elif format == "modelviewset": generator = ModelViewSetGenerator(app_config, force) else: message = "'%s' is not a valid format. " % options["format"] message += "(viewset, modelviewset, apiview, function)" raise CommandError(message) if serializers: result = generator.generate_serializers(depth) elif views: result = generator.generate_views() elif urls: result = generator.generate_urls() else: result = generator.generate_serializers(depth) + "\n" result += generator.generate_views() + "\n" result += generator.generate_urls() print(result)
def import_crud(app): """ Import moderator module and register all models it contains with moderation """ try: app_path = import_module(app).__path__ except (AttributeError, ImportError): return None try: imp.find_module("crud", app_path) except ImportError: return None module = import_module("%s.crud" % app) return module
def get_channel_routings(): channel_routing = [] for app in settings.INSTALLED_APPS: try: routing = import_module("{}.routing".format(app)) channel_routing.extend(routing.channel_routing) except: continue return channel_routing
def autodiscover(self, module=None): """ Accepts either no arguements or the name of the module to check. It then looks at each of the ``INSTALLED_APPS`` for the given module name or with the same named as ``discovermodule`` to find any registered subclasses. """ if not module: module = self.discovermodule for app in settings.INSTALLED_APPS: try: import_module(".%s" % module, app) except ImportError: if module_has_submodule(import_module(app), module): raise continue
def import_crud(app): ''' Import crud module and register all model cruds which it contains ''' try: app_path = import_module(app).__path__ except (AttributeError, ImportError): return None try: imp.find_module('crud', app_path) except ImportError: return None module = import_module("%s.crud" % app) return module
def editor(self): try: root_module_name = ".".join(self.__module__.split('.')[:-1]) module_editor = import_module(root_module_name + ".editors") class_name = self.__class__.__name__ + "Editor" class_editor = getattr(module_editor, class_name) return class_editor(self) except (ImportError, AttributeError): return LucteriosEditor(self)
def get_media_dirs(): media_dirs = GLOBAL_MEDIA_DIRS[:] for app in settings.INSTALLED_APPS: if app in IGNORE_APP_MEDIA_DIRS: continue for name in (u'static', u'media'): app_root = os.path.dirname(import_module(app).__file__) media_dirs.append(os.path.join(app_root, name)) return media_dirs