Esempio n. 1
0
def load_module(app):
    for dir in os.listdir("."):
        if os.path.isdir(dir) and re.match(r"(.*)_api", dir) is not None:
            for name in find_modules(dir):
                module = import_string(name)
                print("Loading API Module: %s" % name)
                app.register_blueprint(module.blue_print, url_prefix="/giftPacks/api")
Esempio n. 2
0
def import_module_from_packages(name, app=None, packages=None, silent=False):
    if packages is None:
        if app is None and has_app_context():
            app = current_app
        if app is None:
            raise Exception(
                'Working outside application context or provide app'
            )
        #FIXME
        packages = app.config.get('PACKAGES', [])

    for package in packages:
        if package.endswith('.*'):
            for module in find_modules(package[:-2], include_packages=True):
                try:
                    yield import_string(module + '.' + name, silent)
                except ImportError:
                    pass
                except Exception as e:
                    import traceback
                    traceback.print_exc()
                    app.logger.error('Could not import: "%s.%s: %s',
                                     module, name, str(e))
                    pass
            continue
        try:
            yield import_string(package + '.' + name, silent)
        except ImportError:
            pass
        except Exception as e:
            import traceback
            traceback.print_exc()
            app.logger.error('Could not import: "%s.%s: %s',
                             package, name, str(e))
            pass
Esempio n. 3
0
def register_blueprints(app):
    for name in find_modules('blog.views'):
        mod = import_string(name)
        if hasattr(mod, 'bp'):
            app.register_blueprint(mod.bp)
    app.add_url_rule('/graphql', view_func=GraphQLView.as_view(
        'graphql', schema=schema, graphiql=True))
Esempio n. 4
0
    def autodiscover(self, paths, models=None, module_names=None):
        """
        Automatically register all Kibble views under ``path``.

        :param paths: The module paths to search under.
        :param module_names: A list of module names to match on. e.g. `kibble`
            will only attempt to autodiscover `kibble.py` files.
        :param models: A list of model kinds (either a ``ndb.Model`` subclass
            or a string) (Optional)
        """
        from werkzeug.utils import find_modules, import_string
        from .base import KibbleMeta

        all_models = models is None
        models = [
            (x._kind() if isinstance(x, ndb.Model) else x)
            for x in models or []]

        for p in paths:
            for mod in find_modules(p, True, True):
                # logger.debug("Autodiscover: %s", mod)
                if module_names is None \
                        or mod.rsplit('.', 1)[-1] in module_names:
                    import_string(mod)

        for view in KibbleMeta._autodiscover:
            if view.model and (all_models or view.kind() in models):
                self.register_view(view)
Esempio n. 5
0
def load_providers_config():
  providers = {}
  for pkg in werk_utils.find_modules('%s.providers' % __package__, True):
    cfg = werk_utils.import_string('%s.CONFIG' % pkg, True)
    if cfg and cfg.get('name'):
        providers[cfg['name']] = cfg
  return providers
Esempio n. 6
0
def create_app():
    from flask import Flask
    app = Flask(__name__)

    from web.common.setting import Config
    app.config.from_object(Config)

    from flask_sqlalchemy import SQLAlchemy
    orm = SQLAlchemy(app)

    from web.common.utils import DBUtil
    db = DBUtil(orm)

    app.db = db
    """
        批量注册蓝图
        find_modules:查找指定包下面的所有模块
        参数说明:
        import_path:包路径
        include_packages:若为True则返回包内的子包,默认False
        recursive:是否递归搜索子包,默认False
    """
    from werkzeug.utils import find_modules, import_string
    for module_name in find_modules("web", recursive=True):
        """
            import_string:动态导入需要的模块或对象
            参数说明:
            import_name:要导入的模块或对象名称
            silent:若为True则忽略导入错误,返回None,默认False
        """
        module = import_string(module_name)
        if hasattr(module, "bp"):
            app.register_blueprint(module.bp)

    return app
Esempio n. 7
0
def register_blueprints(app):
    for name in find_modules('dmeetup.blueprints'):
        mod = import_string(name)
        if hasattr(mod, 'bp'):
            prefix = "/{}".format(mod.bp.name)
            app.register_blueprint(mod.bp, url_prefix=prefix)
    return None
Esempio n. 8
0
def iter_suites(name=None):
    name = name or __name__

    for module in find_modules(name):
        mod = import_string(module)
        if hasattr(mod, 'suite'):
            yield mod.suite()
Esempio n. 9
0
def register_blueprints(app):
    for name in find_modules('capitan.blueprints'):
        mod = import_string(name)
        if hasattr(mod, 'bp'):
            url_prefix = mod.url_prefix if hasattr(mod, 'url_prefix') else None
            app.register_blueprint(mod.bp, url_prefix=url_prefix)
    return None
Esempio n. 10
0
    def load_generators(cls, pkg_root, exclude_pkgs, for_modules=[]):

        cls.registry = dict()

        all_modules = []

        all_modules += find_modules(pkg_root, False, True)

        # If specific modules are to be tested, exclude others
        if len(for_modules) > 0:
            all_modules = [module_name
                           for module_name in all_modules
                           for fmod in for_modules
                           if module_name.endswith(fmod)]

        # Check for SERVER mode
        for module_name in all_modules:
            try:
                if "tests." in str(module_name) and not any(
                    str(module_name).startswith(
                        'pgadmin.' + str(exclude_pkg)
                    ) for exclude_pkg in exclude_pkgs
                ):
                    import_module(module_name)
            except ImportError:
                traceback.print_exc(file=sys.stderr)
Esempio n. 11
0
def register_blueprints(app):
    from werkzeug.utils import find_modules, import_string
    for name in find_modules(__name__, include_packages=True, recursive=True):
        mod = import_string(name)
        if hasattr(mod, 'bp'):
            app.register_blueprint(mod.bp)
    return None
Esempio n. 12
0
def register_blueprints(app):
    """蓝图注册"""
    for name in find_modules('blueprints'):
        mod = import_string(name)
        if hasattr(mod, 'bp'):
            app.register_blueprint(mod.bp)
    return None
Esempio n. 13
0
def import_module_from_packages(name, app=None, packages=None, silent=False):
    """Import modules from packages."""
    warnings.warn("Use of import_module_from_packages has been deprecated."
                  " Please use Flask-Registry instead.",  DeprecationWarning)

    if app is None and has_app_context():
        app = current_app
    if app is None:
        raise Exception(
            'Working outside application context or provide app'
        )

    if packages is None:
        packages = app.config.get('PACKAGES', [])

    for package in packages:
        if package.endswith('.*'):
            for module in find_modules(package[:-2], include_packages=True):
                try:
                    yield import_string(module + '.' + name, silent)
                except ImportError:
                    pass
                except Exception:
                    app.logger.exception("could not import %s.%s",
                                         package, name)
            continue
        try:
            yield import_string(package + '.' + name, silent)
        except ImportError:
            pass
        except Exception:
            app.logger.exception("could not import %s.%s", package, name)
Esempio n. 14
0
def register_blueprints():
    """Register all service modules."""
    for name in find_modules('mini.blueprints'):
        mod = import_string(name)
        if hasattr(mod, 'bp'):
            app.register_blueprint(mod.bp, url_prefix='/' + mod.bp.name)
    return None
Esempio n. 15
0
def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__)

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_object('proj.config')
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # replace secret key from config with random value
    secret_key = app.config.get('SECRET_KEY', None)
    app.config['SECRET_KEY'] = uuid.uuid4(
    ).hex if secret_key is None else secret_key

    # init celery
    celery.init_app(app)

    # init database
    db.init_app(app)

    # register all blueprints
    for name in find_modules('proj.view', recursive=True):
        mod = import_string(name)
        if hasattr(mod, 'view'):
            app.register_blueprint(mod.view)

    return app
Esempio n. 16
0
    def _discover_module(self, pkg):
        import_str = pkg + '.' + self.module_name

        blacklist = self.app.config.get(
            '%s_%s_EXCLUDE' % (self.cfg_var_prefix, self.module_name.upper()),
            []
        )

        try:
            import_string(import_str, silent=self.silent)
        except ImportError as e:  # pylint: disable=C0103
            self._handle_importerror(e, pkg, import_str)
            return
        except SyntaxError as e:
            self._handle_syntaxerror(e, pkg, import_str)
            return

        for m in find_modules(import_str):
            if m in blacklist:  # Exclude specific package
                continue
            try:
                module = import_string(m, silent=self.silent)
                if module is not None:
                    self.register(module)
            except ImportError as e:  # pylint: disable=C0103
                self._handle_importerror(e, import_str, m)
            except SyntaxError as e:
                self._handle_syntaxerror(e, import_str, m)
Esempio n. 17
0
def iter_suites(name=None):
    name = name or __name__

    for module in find_modules(name):
        mod = import_string(module)
        if hasattr(mod, 'suite'):
            yield mod.suite()
Esempio n. 18
0
def register_blueprints(app):
    from event_api.blueprints import events, swagger
    for name in find_modules('event_api.blueprints'):
        mod = import_string(name)
        if hasattr(mod, 'bp'):
            app.register_blueprint(mod.bp)
    return None
Esempio n. 19
0
def register_manager(manager):
    """Register all manager plugins and default commands with the manager."""
    from six.moves.urllib.parse import urlparse
    managers = RegistryProxy('managers', ModuleAutoDiscoveryRegistry, 'manage')

    with manager.app.app_context():
        for script in find_modules('invenio.base.scripts'):
            manager.add_command(script.split('.')[-1],
                                import_string(script + ':manager'))
        for script in managers:
            if script.__name__ == 'invenio.base.manage':
                continue
            manager.add_command(script.__name__.split('.')[-2],
                                getattr(script, 'manager'))

    manager.add_command("clean", Clean())
    manager.add_command("show-urls", ShowUrls())
    manager.add_command("shell", Shell())
    parsed_url = urlparse(manager.app.config.get('CFG_SITE_URL'))
    port = parsed_url.port or 80
    host = parsed_url.hostname or '127.0.0.1'
    runserver = Server(host=host, port=port)
    manager.add_command("runserver", runserver)

    # FIXME separation of concerns is violated here.
    from invenio.ext.collect import collect
    collect.init_script(manager)

    from invenio.ext.assets import command, bower
    manager.add_command("assets", command)
    manager.add_command("bower", bower)
Esempio n. 20
0
    def load_controllers(self):
        """Load all controllers from the application, so the routing cache gets
        filled."""
        for mod in find_modules(self.appname+".controllers"):
            self.controllers[mod.split('.')[-1]] = __import__(mod, None, None, ['']).controller

        self.loaded_controllers = True
Esempio n. 21
0
def register_manager(manager):
    """Register all manager plugins and default commands with the manager."""
    from six.moves.urllib.parse import urlparse
    from flask.ext.script.commands import Shell, Server, ShowUrls, Clean
    managers = RegistryProxy('managers', ModuleAutoDiscoveryRegistry, 'manage')

    with manager.app.app_context():
        for script in find_modules('invenio.base.scripts'):
            manager.add_command(script.split('.')[-1],
                                import_string(script + ':manager'))
        for script in managers:
            if script.__name__ == 'invenio.base.manage':
                continue
            manager.add_command(script.__name__.split('.')[-2],
                                getattr(script, 'manager'))

    manager.add_command("clean", Clean())
    manager.add_command("show-urls", ShowUrls())
    manager.add_command("shell", Shell())
    parsed_url = urlparse(manager.app.config.get('CFG_SITE_URL'))
    port = parsed_url.port or 80
    host = parsed_url.hostname or '127.0.0.1'
    manager.add_command("runserver", Server(host=host, port=port))

    from invenio.ext.collect import collect
    collect.init_script(manager)

    # Added for B2SHARE for debugging purposes
    print("Available blueprints:", [x.name for x in manager.app.blueprints.values()])
Esempio n. 22
0
def iter_suites(packages=None):
    """Yield all testsuites."""
    from werkzeug.utils import import_string, find_modules
    from flask_registry import ModuleAutoDiscoveryRegistry, \
        ImportPathRegistry

    app = create_app()

    if packages is None:
        testsuite = ModuleAutoDiscoveryRegistry('testsuite', app=app)
        from invenio import testsuite as testsuite_invenio
        from invenio.base import testsuite as testsuite_base
        from invenio.celery import testsuite as testsuite_celery
        testsuite.register(testsuite_invenio)
        testsuite.register(testsuite_base)
        testsuite.register(testsuite_celery)
    else:
        exclude = map(lambda x: x + '.testsuite',
                      app.config.get('PACKAGES_EXCLUDE', []))
        testsuite = ImportPathRegistry(initial=packages,
                                       exclude=exclude,
                                       load_modules=True)

    for package in testsuite:
        for name in find_modules(package.__name__):
            module = import_string(name)
            if not module.__name__.split('.')[-1].startswith('test_'):
                continue
            if hasattr(module, 'TEST_SUITE'):
                yield module.TEST_SUITE
            else:
                app.logger.warning("%s: No test suite defined." %
                                   module.__name__)
Esempio n. 23
0
def iter_suites(packages=None):
    """Yield all testsuites."""
    from werkzeug.utils import import_string, find_modules
    from flask_registry import ModuleAutoDiscoveryRegistry, \
        ImportPathRegistry

    app = create_app()

    if packages is None:
        testsuite = ModuleAutoDiscoveryRegistry('testsuite', app=app)
        from invenio import testsuite as testsuite_invenio
        testsuite.register(testsuite_invenio)
    else:
        exclude = map(lambda x: x + '.testsuite',
                      app.config.get('PACKAGES_EXCLUDE', []))
        testsuite = ImportPathRegistry(initial=packages, exclude=exclude,
                                       load_modules=True)

    for package in testsuite:
        for name in find_modules(package.__name__):
            module = import_string(name)
            if not module.__name__.split('.')[-1].startswith('test_'):
                continue
            if hasattr(module, 'TEST_SUITE'):
                yield module.TEST_SUITE
            else:
                app.logger.warning(
                    "%s: No test suite defined." % module.__name__)
Esempio n. 24
0
def register_blueprints(app):
    """Register all blueprint modules."""
    for name in find_modules('ET_Flask.blueprints'):
        mod = import_string(name)
        if hasattr(mod, 'bp'):
            app.register_blueprint(mod.bp)
    return None
Esempio n. 25
0
    def _load_resource(self, typename):
        bp_settings_path = ((self.app.config.get('BLUEPRINTS', None)
                             and 'BLUEPRINTS') or
                            (self.app.config.get('INSTALLED_BLUEPRINTS', None)
                             and 'INSTALLED_BLUEPRINTS') or False)
        if not bp_settings_path:
            raise NoInstalledBlueprintsSettingException(
                'You must have a setting for either INSTALLED_BLUEPRINTS or BLUEPRINTS'
            )
        for blueprint_path in self.app.config.get(bp_settings_path, []):
            module_name, object_name = blueprint_path.rsplit('.', 1)
            blueprint_module, bp_name = self._get_imported_stuff_by_path(
                blueprint_path)
            blueprint = getattr(blueprint_module, bp_name)
            modules = find_modules(module_name)
            for module in modules:
                if typename in module:
                    mod = import_string(module)
                    for itm in dir(mod):
                        cls = getattr(mod, itm)
                        if self._is_public_attr(itm) and\
                                itm[0] == str(itm[0]).upper() and\
                                'class' in str(cls) and\
                                'view' in str(itm).lower():

                            if hasattr(cls,'_add_default_routes') and\
                                    getattr(cls,'_default_view_routes'):
                                if is_verbose():
                                    print 'getting default routes for ', cls.__name__
                                getattr(cls, '_add_default_routes')(
                                    app=blueprint or self.app)
Esempio n. 26
0
    def _discover_module(self, pkg):
        import_str = pkg + '.' + self.module_name

        blacklist = self.app.config.get(
            '%s_%s_EXCLUDE' % (self.cfg_var_prefix, self.module_name.upper()),
            [])

        try:
            import_string(import_str, silent=self.silent)
        except ImportError as e:  # pylint: disable=C0103
            self._handle_importerror(e, pkg, import_str)
            return
        except SyntaxError as e:
            self._handle_syntaxerror(e, pkg, import_str)
            return

        for m in find_modules(import_str):
            if m in blacklist:  # Exclude specific package
                continue
            try:
                module = import_string(m, silent=self.silent)
                if module is not None:
                    self.register(module)
            except ImportError as e:  # pylint: disable=C0103
                self._handle_importerror(e, import_str, m)
            except SyntaxError as e:
                self._handle_syntaxerror(e, import_str, m)
Esempio n. 27
0
def register_blueprints(app):
    "register blueprints"
    for name in find_modules('mongo_flask.blueprints'):
        mod = import_string(name)
        if hasattr(mod, 'bp') and hasattr(mod, 'url_prefix'):
            app.register_blueprint(mod.bp, url_prefix=mod.url_prefix)
    return
Esempio n. 28
0
def register_manager(manager):
    """Register all manager plugins and default commands with the manager."""
    from six.moves.urllib.parse import urlparse
    managers = RegistryProxy('managers', ModuleAutoDiscoveryRegistry, 'manage')

    with manager.app.app_context():
        for script in find_modules('invenio.base.scripts'):
            manager.add_command(
                script.split('.')[-1], import_string(script + ':manager'))
        for script in managers:
            if script.__name__ == 'invenio.base.manage':
                continue
            manager.add_command(
                script.__name__.split('.')[-2], getattr(script, 'manager'))

    manager.add_command("clean", Clean())
    manager.add_command("show-urls", ShowUrls())
    manager.add_command("shell", Shell())
    parsed_url = urlparse(manager.app.config.get('CFG_SITE_URL'))
    host = manager.app.config.get('SERVER_BIND_ADDRESS', parsed_url.hostname
                                  or '127.0.0.1')
    port = manager.app.config.get('SERVER_BIND_PORT', parsed_url.port or 80)
    runserver = Server(host=host, port=port)
    manager.add_command("runserver", runserver)

    # FIXME separation of concerns is violated here.
    from invenio.ext.collect import collect
    collect.init_script(manager)

    from invenio.ext.assets import command, bower
    manager.add_command("assets", command)
    manager.add_command("bower", bower)
Esempio n. 29
0
def register_blueprints(app):
    for name in find_modules('app.blueprints'):
        mod = import_string(name)
        name = name.split(".")[-1]
        #name of the variable used to store the blueprint
        if hasattr(mod, name):
            app.register_blueprint(getattr(mod, name))
    return None
Esempio n. 30
0
def register_blueprints(app, package=None):
    if package is None:
        raise ValueError('package parameter not be None')

    for name in find_modules(package):
        mod = import_string(name)
        if hasattr(mod, 'app') and isinstance(mod.app, Blueprint):
            app.register_blueprint(mod.app)
Esempio n. 31
0
def register_blueprints(app):
    """register all blueprints in the blueprints folder.
    It will look for an object named "blueprint" in those files."""
    for blueprint in next(walk("blueprints"))[1]:
        for name in find_modules(f"blueprints.{blueprint}"):
            mod = import_string(name)
            if hasattr(mod, "blueprint"):
                app.register_blueprint(mod.blueprint)
Esempio n. 32
0
def register_blueprints(app):
    """Register Flask blueprints."""
    for name in find_modules('app.blueprints'):
        mod = import_string(name)
        if hasattr(mod, 'public_pb'):
            app.register_blueprint(mod.public_pb)

    return None
Esempio n. 33
0
def register_blueprints(root, app):
    for name in find_modules(root, recursive=True):
        mod = import_string(name)
        if hasattr(mod, 'bp'):
            uri = name.split('.')
            version = uri[2].replace('_', '.')
            prefix = '/{0}/{1}'.format(uri[1], version)
            app.register_blueprint(mod.bp, url_prefix=prefix)
Esempio n. 34
0
def register_all_blueprints(app, blueprint_module):
    if blueprint_module:
        for name in find_modules(blueprint_module, include_packages=True, recursive=True):
            mod = import_string(name)
            for item_name in dir(mod):
                item = getattr(mod, item_name)
                if isinstance(item, Blueprint):
                    app.register_blueprint(item)
Esempio n. 35
0
def register_api(api):
  for pkg in w_utils.find_modules('apps', True):
    pkg_api = '%s.api' % pkg
    resources = get_module_obj(pkg_api, 'API')
    if not resources:
      continue
    for resource in resources:
      register_api_resource(api, resource)
Esempio n. 36
0
def register_blueprints(app, v, package):
    for module_name in find_modules(package):
        module = import_string(module_name)
        if hasattr(module, 'bp'):
            bp = module.bp
            app.register_blueprint(bp,
                                   url_prefix='/api/{0}/{1}'.format(
                                       v, bp.name))
Esempio n. 37
0
def register_elements(package):
    """Register additional stuff

    Args:
        package (str): package name
    """
    for name in find_modules('{}.{}'.format(APPNAME, package)):
        import_string(name)
Esempio n. 38
0
def register_apps(app):
  for pkg in w_utils.find_modules('apps', True):
    pkg_views = '%s.views' % pkg
    objs = [get_module_obj(pkg_views, obj) for obj in ['bpa', 'bp']]
    funcy.walk(funcy.silent(app.register_blueprint), objs)
    app_init = get_module_obj(pkg, 'app_init')
    if app_init:
      app_init(app)
Esempio n. 39
0
def register_blueprints(root, _app):
    """注册蓝图

    """
    for name in find_modules(root, recursive=True):
        mod = import_string(name)
        if hasattr(mod, 'bp'):
            _app.register_blueprint(mod.bp)
Esempio n. 40
0
def auto_get_urlpatterns():
    urlpatterns = []
    for mod in find_modules("apps", recursive=True):
        if str(mod).endswith("urls"):
            model = import_string(mod)
            if hasattr(model, "urlpatterns") and isinstance(
                    model.urlpatterns, list):
                urlpatterns += model.urlpatterns
    return urlpatterns
Esempio n. 41
0
def register_blueprints(app):
    """Register all blueprint modules
    Reference: Armin Ronacher, "Flask for Fun and for Profit" PyBay 2016.
    """
    for name in find_modules('scenemanagement.scene'):
        mod = import_string(name)
        if hasattr(mod, 'bp'):
            app.register_blueprint(mod.bp)
    return None
Esempio n. 42
0
    def load_generators(cls, pkg):

        cls.registry = dict()

        from importlib import import_module
        from werkzeug.utils import find_modules

        for module_name in find_modules(pkg, False, True):
            module = import_module(module_name)
Esempio n. 43
0
def register_blueprints(app):
    """Register all blueprint modules
    Reference: Armin Ronacher, "Flask for Fun and for Profit" PyBay 2016.
    """
    for name in find_modules('flaskr.blueprints'):
        mod = import_string(name)
        if hasattr(mod, 'bp'):
            app.register_blueprint(mod.bp)
    return None
Esempio n. 44
0
    def load_generators(cls, pkg):

        cls.registry = dict()

        from importlib import import_module
        from werkzeug.utils import find_modules

        for module_name in find_modules(pkg, False, True):
            module = import_module(module_name)
Esempio n. 45
0
    def is_module_exist(self):
        """Checks if module exists by the module name as the parameter:

               is_module_exist('app.views')

        Throws the error string to the console output if no module found
        but doesn't raise any exception. Returns bool value.
        """
        error_map = {'settings': NO_SETTINGS_ERROR}
        try:
            find_modules(self.module_name)
            return True
        except ImportError:
            if self.module_name in error_map.keys():
                sys.stderr.write(error_map[self.module_name])
            else:
                sys.stderr.write(NO_MODULE_COMMON_ERROR.format(self.module_name))
            return False
Esempio n. 46
0
def register_blueprints(app):
    """Register all blueprint modules
    Reference: Armin Ronacher, "Flask for Fun and for Profit" PyBay 2016.
    """
    for name in find_modules("thefort.blueprints"):
        mod = import_string(name)
        if hasattr(mod, "bp"):
            app.register_blueprint(mod.bp)
    return None
Esempio n. 47
0
    def load_drivers(cls):
        # Initialize the registry only if it has not yet been initialized
        if DriverRegistry.registry is None:
            DriverRegistry.registry = dict()

        from importlib import import_module
        from werkzeug.utils import find_modules

        for module_name in find_modules(__package__, True):
            module = import_module(module_name)
Esempio n. 48
0
 def load_models(self):
     """Recursivly import all models from our application, so SQLAlchemy can
     track them and we can create_all() them. (;"""
     
     try:
         for mod in find_modules(self.appname+".models"):
             __import__(mod, None, None, [''])
     except ValueError:
         # Models is not a package, so we treat it as module
         self.application.import_from_app("models")
Esempio n. 49
0
def iter_builtin_plugins():
    """Iterates over all built-in plugins that exist in Lektor."""
    for module in find_modules('lektor.plugins', include_packages=True):
        mod = import_string(module)
        for key, value in mod.__dict__.iteritems():
            try:
                if key[:1] != '_' and value is not Plugin and \
                   issubclass(value, Plugin):
                    yield 'core-' + module.split('.')[-1], value
            except TypeError:
                pass
Esempio n. 50
0
 def find_submodules(self, basemodule):
     for module_name in find_modules(basemodule, True):
         if module_name in self.config['MODULE_BLACKLIST']:
             self.logger.info('Skipping blacklisted module: %s' %
                             module_name)
             continue
         self.logger.info('Examining potential module: %s' % module_name)
         module = import_module(module_name)
         for key, value in module.__dict__.items():
             if isinstance(value, PgAdminModule):
                 yield value
Esempio n. 51
0
    def configure_packages(self, packages):
        for package_name in packages:
            package_name = '%s.%s' % (self.import_name, package_name)
            modules = find_modules(package_name)
            for module in modules:
                __import__(module)

            package = import_string(package_name)
            for attr_name in dir(package):
                attr = getattr(package, attr_name)
                if isinstance(attr, Blueprint):
                    self.register_blueprint(attr)
Esempio n. 52
0
    def __gen_task_include(package_name):
        """ scan miitus/srv/tasks folder to include those modules """
        if not isinstance(package_name, string_types):
            raise TypeError(
                'Only accept string-types for package_name, not:' + str(package_name)
            )

        ret = []
        for name in find_modules(package_name, recursive=True):
            ret.append(name)

        return ret
Esempio n. 53
0
def import_submodules_from_packages(name, app=None, packages=None,
                                    silent=False):
    discover = partial(import_module_from_packages, name)
    out = []
    for p in discover(app=app, packages=packages, silent=silent):
        if p is not None:
            for m in find_modules(p.__name__):
                try:
                    out.append(import_string(m, silent))
                except Exception as e:
                    if not silent:
                        raise e
    return out
Esempio n. 54
0
def register_manager(manager):
    """Register all manager plugins and default commands with the manager."""
    from six.moves.urllib.parse import urlparse
    managers = RegistryProxy('managers', ModuleAutoDiscoveryRegistry, 'manage')

    def extract_name(name):
        """Guess manager name."""
        parts = name.split('.')
        if len(parts) == 2:
            return parts[0].split('_')[-1]
        return parts[-2]

    with manager.app.app_context():
        for script in find_modules('invenio_base.scripts'):
            manager.add_command(script.split('.')[-1],
                                import_string(script + ':manager'))
        for script in managers:
            if script.__name__ == 'invenio_base.manage':
                continue
            manager.add_command(extract_name(script.__name__),
                                getattr(script, 'manager'))

    manager.add_command("clean", Clean())
    manager.add_command("show-urls", ShowUrls())
    manager.add_command("shell", Shell())

    parsed_url = urlparse(manager.app.config.get('CFG_SITE_URL'))
    host = manager.app.config.get(
        'SERVER_BIND_ADDRESS',
        parsed_url.hostname or '127.0.0.1'
    )
    port = manager.app.config.get(
        'SERVER_BIND_PORT',
        parsed_url.port or 80
    )

    ssl_context = create_ssl_context(manager.app.config)

    runserver = Server(host=host, port=port, ssl_context=ssl_context)
    manager.add_command("runserver", runserver)

    # FIXME separation of concerns is violated here.
    from invenio_ext.collect import collect
    collect.init_script(manager)

    from invenio_ext.assets import command, bower
    manager.add_command("assets", command)
    manager.add_command("bower", bower)
Esempio n. 55
0
def prepare_db():
    """
    """
    global c

    # init keyspace
    # TODO: replication-factor:1 is just a dev config
    create_keyspace(const.CQL_KEYSPACE_NAME, replication_factor=1)

    # sync table
    for name in find_modules(const.MODEL_PACKAGE_ROOT, recursive=True):
        mod = import_string(name)
        for item_name in dir(mod):
            item = getattr(mod, item_name)
            if type(item) == ModelMetaClass and issubclass(item, Model) and item.__name__ != 'Model':
                sync_table(item)
Esempio n. 56
0
    def register(self, import_path):
        """
        Register a new import path

        :param import_path: A full Python import path (e.g.
            ``somepackge.somemodule``) or Python star import path to find all
            modules inside a package (e.g. ``somepackge.*``).
        """
        if import_path.endswith('.*'):
            for mod_path in find_modules(import_path[:-2],
                                         include_packages=True):
                super(ImportPathRegistry, self).register(
                    self._load_import_path(mod_path)
                )
        else:
            super(ImportPathRegistry, self).register(
                self._load_import_path(import_path)
            )
Esempio n. 57
0
    def load_generators(cls, pkg_root, exclude_pkgs):

        cls.registry = dict()

        all_modules = []

        all_modules += find_modules(pkg_root, False, True)

        # Check for SERVER mode
        for module_name in all_modules:
            try:
                if "tests." in str(module_name) and not any(
                    str(module_name).startswith(
                        'pgadmin.' + str(exclude_pkg)
                    ) for exclude_pkg in exclude_pkgs
                ):
                    import_module(module_name)
            except ImportError:
                traceback.print_exc(file=sys.stderr)
Esempio n. 58
0
    def _handle_importerror(self, exception, pkg, import_str):
        """
        Properly handle an import error

        If a module does not exists, it's not an error, however an
        ImportError generated from importing an existing module is an
        error.
        """
        try:
            for found_module_name in find_modules(pkg):
                if found_module_name == import_str:
                    reraise(
                        ImportError,
                        ImportError(*exception.args),
                        sys.exc_info()[2]
                    )
        except ValueError:
            # pkg doesn't exist or is not a package
            pass
Esempio n. 59
0
    def _discover_module(self, pkg):
        """
        Method to discover a single module. May be overwritten by subclasses.
        """
        import_str = pkg + '.' + self.module_name

        try:
            module = import_string(import_str, self.silent)
            self.register(module)
        except ImportError as e:  # pylint: disable=C0103
            # If a module does not exists, it's not an error, however an
            # ImportError generated from importing an existing module is an
            # error.
            try:
                for found_module_name in find_modules(pkg):
                    if found_module_name == import_str:
                        reraise(
                            ImportError,
                            ImportError(*e.args),
                            sys.exc_info()[2]
                        )
            except ValueError:
                # pkg doesn't exist or is not a package
                pass