コード例 #1
0
def run(output):
    """Convert *bfo* to *yml*."""
    from invenio.legacy.dbquery import run_sql
    from flask_registry import PkgResourcesDirDiscoveryRegistry, \
        ModuleAutoDiscoveryRegistry, RegistryProxy
    from invenio.utils.datastructures import LazyDict

    output_formats_directories = RegistryProxy(
        'legacy_output_formats_directories',
        ModuleAutoDiscoveryRegistry,
        'output_formats'
    )

    output_formats = RegistryProxy(
        'legacy_output_formats',
        PkgResourcesDirDiscoveryRegistry,
        '.', registry_namespace=output_formats_directories
    )

    def create_output_formats_lookup():
        """Create output formats."""
        out = {}

        for f in output_formats:
            of = os.path.basename(f).lower()
            if not of.endswith('.bfo'):
                continue
            of = of[:-4]
            if of in out:
                continue
            out[of] = f
        return out

    output_formats_lookup = LazyDict(create_output_formats_lookup)

    for row in run_sql('SELECT id, name, code, description, content_type, '
                       ' mime_type, visibility FROM format'):
        code = row[2].lower()
        out = {
            'name': row[1],
            'description': row[3],
            'visibility': 1 if row[6] == '1' else 0,
            'content_type': row[4],
        }
        if row[5]:
            out['mime_type'] = row[5]

        try:
            out.update(get_output_format(output_formats_lookup[code]))
            with open(os.path.join(output, code + '.yml'), 'w') as f:
                yaml.dump(out, stream=f)
            # print('echo "{0}" > {1}/{2}.yml'.format(
            #     yaml.dump(out), output, code))
        except Exception:
            current_app.logger.exception(
                "Could not convert '{0}'".format(code)
            )
コード例 #2
0
 def test_proxy_noregistry(self):
     proxy = RegistryProxy('prxns', RegistryBase)
     with self.app.app_context():
         try:
             proxy.register()
             raise AssertionError(
                 "Registry is supposed not to be avialable")
         except RegistryError:
             pass
コード例 #3
0
 def test_proxy_noregistry(self):
     proxy = RegistryProxy('prxns', RegistryBase)
     with self.app.app_context():
         try:
             proxy.register()
             raise AssertionError(
                 "Registry is supposed not to be avialable"
             )
         except RegistryError:
             pass
コード例 #4
0
ファイル: __init__.py プロジェクト: chokribr/invenio-1
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)
コード例 #5
0
def _get_test_taxonomies():
    TEST_PACKAGES = ['invenio_classifier', 'demo_package']

    test_registry = RegistryProxy('test_registry',
                                  ImportPathRegistry,
                                  initial=TEST_PACKAGES)
    return PkgResourcesDirDiscoveryRegistry('taxonomies',
                                            registry_namespace=test_registry)
コード例 #6
0
    def test_proxy(self):
        Registry(app=self.app)
        proxy = RegistryProxy('prxns', RegistryBase)

        assert 'prxns' not in self.app.extensions['registry']

        with self.app.app_context():
            self.assertRaises(NotImplementedError, proxy.register)
            assert 'prxns' in self.app.extensions['registry']
            assert isinstance(self.app.extensions['registry']['prxns'],
                              RegistryBase)
コード例 #7
0
    def test_registry_proxy(self):
        Registry(app=self.app)

        self.app.extensions['registry']['pathns'] = \
            ImportPathRegistry(initial=['flask_registry.*'])

        myns = RegistryProxy(
            'myns', ModuleAutoDiscoveryRegistry, 'appdiscovery',
            registry_namespace='pathns'
        )

        with self.app.app_context():
            self.assertEqual(4, len(self.app.extensions['registry']['pathns']))
            self.assertEqual(1, len(list(myns)))
            from flask_registry.registries import appdiscovery
            self.assertEqual(appdiscovery, myns[0])
コード例 #8
0
ファイル: engine.py プロジェクト: jirikuncar/invenio-upgrader
    def __init__(self,
                 packages=None,
                 global_pre_upgrade=None,
                 global_post_upgrade=None):
        """Init.

        @param global_pre_upgrade: List of callables. Each check will be
            executed once per upgrade-batch run. Useful e.g. to check if
            bibsched is running.
        @param global_post_upgrade: List of callables. Each check will be
            executed once per upgrade-batch run. Useful e.g. to tell users
            to start bibsched again.
        """
        self.upgrades = None
        self.history = {}
        self.ordered_history = []

        self.global_pre_upgrade = global_pre_upgrade or []
        self.global_post_upgrade = global_post_upgrade or [post_check_bibsched]
        if packages is None:
            self.packages = current_app.extensions['registry']['packages']
        else:
            self.packages = RegistryProxy('upgrader.packages',
                                          ImportPathRegistry,
                                          initial=packages)

        # Warning related
        self.old_showwarning = None
        self.warning_occured = 0
        self._logger = None
        self._logger_file_fmtter = InvenioUpgraderLogFormatter(
            self.FILE_LOG_FMT)
        self._logger_console_fmtter = InvenioUpgraderLogFormatter(
            self.CONSOLE_LOG_FMT,
            info=self.CONSOLE_LOG_INFO_FMT,
        )
コード例 #9
0
    def test_proxy_ns(self):
        Registry(app=self.app)

        proxy = RegistryProxy(
            'pathns',
            ImportPathRegistry,
            initial=['flask_registry.*']
        )

        with self.app.app_context():
            assert 'pathns' not in self.app.extensions['registry']

            self.app.extensions['registry']['myns'] = \
                ModuleDiscoveryRegistry('appdiscovery',
                                        registry_namespace=proxy)

            assert 'pathns' in self.app.extensions['registry']
            self.assertEqual(4, len(self.app.extensions['registry']['pathns']))

            self.app.extensions['registry']['myns'].discover()

            assert len(self.app.extensions['registry']['myns']) == 1
            from flask_registry.registries import appdiscovery
            assert self.app.extensions['registry']['myns'][0] == appdiscovery
コード例 #10
0
ファイル: registry.py プロジェクト: IFCA/lifewatch_osf
            # Super call with ImportPathRegistry instead of
            # DepositionTypeRegistry on purpose.
            super(ImportPathRegistry, self).register(import_path_or_type)
            workflows[import_path_or_type.__name__] = import_path_or_type
        else:
            super(DepositionTypeRegistry, self).register(import_path_or_type)

    def unregister(self, deposition_type):
        """Allow unregistering deposition types."""
        if deposition_type.__name__ not in workflows:
            raise RegistryError("Deposition type not registered")
        # Super call with ImportPathRegistry instead of DepositionTypeRegistry
        # on purpose.
        super(ImportPathRegistry, self).unregister(deposition_type)
        del workflows[deposition_type.__name__]

    def mapping(self):
        """Define deposition type mapping by their ``__name__``."""
        return dict([(x.__name__, x) for x in self])


deposit_default_type = RegistryProxy('deposit_default_type',
                                     DepositSingletonRegistry)
"""
Registry of a single default deposition type - initialized
by DepositionTypeRegistry
"""

deposit_types = RegistryProxy('deposit_types', DepositionTypeRegistry)
""" Registry of loaded deposition types """
コード例 #11
0
ファイル: registry.py プロジェクト: chokribr/invenio-1
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""Registry for BibDocFile."""

from flask_registry import ImportPathRegistry, RegistryProxy

from invenio.ext.registry import ModuleAutoDiscoverySubRegistry

bibdocfile = RegistryProxy(
    'bibdocfile', ImportPathRegistry,
    initial=['invenio.legacy.bibdocfile']
)

plugins = RegistryProxy('bibdocfile.plugins',
                        ModuleAutoDiscoverySubRegistry,
                        'plugins',
                        registry_namespace=bibdocfile)
コード例 #12
0
assets = Environment()


class BundlesAutoDiscoveryRegistry(ModuleAutoDiscoveryRegistry):

    """Registry that searches for bundles.

    Its registry is a list of the package name and the bundle itself. This way
    you can keep track of where a bundle was loaded from.
    """

    def __init__(self, module_name=None, app=None, with_setup=False,
                 silent=False):
        """Initialize the bundle auto discovery registry.

        :param module_name: where to look for bundles (default: bundles)
        :type module_name: str
        """
        super(BundlesAutoDiscoveryRegistry, self).__init__(
            module_name or 'bundles', app=app, with_setup=with_setup,
            silent=silent)

bundles = RegistryProxy("bundles", BundlesAutoDiscoveryRegistry)


def setup_app(app):
    """Init the extension with app context."""
    assets.init_app(app)
    return app
コード例 #13
0
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Classifier registries."""

import os

from flask_registry import PkgResourcesDirDiscoveryRegistry, \
    ModuleAutoDiscoveryRegistry, RegistryProxy
from invenio.utils.datastructures import LazyDict

classifierext = RegistryProxy('classifierext', ModuleAutoDiscoveryRegistry,
                              'classifierext')

taxonomies_proxy = RegistryProxy('classifierext.taxonomies',
                                 PkgResourcesDirDiscoveryRegistry,
                                 'taxonomies',
                                 registry_namespace=classifierext)

taxonomies = LazyDict(lambda: dict(
    (os.path.basename(f), f) for f in taxonomies_proxy))

kb = LazyDict(lambda: dict((os.path.basename(f), f) for f in RegistryProxy(
    'converterext.kb',
    PkgResourcesDirDiscoveryRegistry,
    'kb',
    registry_namespace=classifierext)))
コード例 #14
0
ファイル: registry.py プロジェクト: jalavik/invenio-records
def function_proxy(namespace):
    return RegistryProxy(namespace + '.functions',
                         ModuleAutoDiscoverySubRegistry,
                         'functions',
                         registry_namespace=jsonext(namespace))
コード例 #15
0
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

from flask_registry import PkgResourcesDirDiscoveryRegistry, \
    ModuleAutoDiscoveryRegistry, RegistryProxy, ImportPathRegistry
from werkzeug.local import LocalProxy

from invenio.utils.datastructures import LazyDict
from invenio.ext.registry import ModuleAutoDiscoverySubRegistry
from invenio.legacy.registry import legacy_modules

ingestion_packages_proxy = RegistryProxy('legacy.bibingest.ingestion_packages',
                                         ModuleAutoDiscoverySubRegistry,
                                         'ingestion_packages',
                                         registry_namespace=legacy_modules)

ingestion_packages = LazyDict(lambda: dict((module.__name__.split('.')[
    -1], module.package) for module in ingestion_packages_proxy))

storage_engines_proxy = RegistryProxy('legacy.bibingest.storage_engines',
                                      ModuleAutoDiscoverySubRegistry,
                                      'storage_engines',
                                      registry_namespace=legacy_modules)

storage_engines = LazyDict(lambda: dict(
    (module.storage_engine.__engine_name__, module.storage_engine)
    for module in storage_engines_proxy))
コード例 #16
0
from flask_registry import PkgResourcesDirDiscoveryRegistry, RegistryProxy, \
    ImportPathRegistry, ModuleAutoDiscoveryRegistry

bibformat = lazy_import('invenio.modules.formatter')
bibformat_engine = lazy_import('invenio.modules.formatter.engine')
bibformat_utils = lazy_import('invenio.modules.formatter.utils')
bibformat_config = lazy_import('invenio.modules.formatter.config')
gettext_set_language = lazy_import('invenio.base.i18n:gettext_set_language')

TEST_PACKAGES = [
    'invenio.modules.formatter.testsuite.overlay',
    'invenio.modules.formatter.testsuite',
]

test_registry = RegistryProxy('test_registry',
                              ImportPathRegistry,
                              initial=TEST_PACKAGES)

output_formats_directories_registry = lambda: ModuleAutoDiscoveryRegistry(
    'output_formats', registry_namespace=test_registry, silent=True)


class OutputFormatTest(InvenioTestCase):
    """ bibformat - tests on output formats"""
    def setUp(self):
        self.app.extensions['registry']['output_formats_directories'] = \
            output_formats_directories_registry()
        from invenio.modules.formatter.registry import output_formats as ofs
        ofs.expunge()

    def tearDown(self):
コード例 #17
0
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

import operator
import os

from flask_registry import PkgResourcesDirDiscoveryRegistry, \
    RegistryProxy, ImportPathRegistry

legacy = RegistryProxy('legacy',
                       ImportPathRegistry,
                       initial=['invenio.legacy.*'])

doc_category = lambda namespace: RegistryProxy(
    'legacy.doc.' + namespace,
    PkgResourcesDirDiscoveryRegistry,
    'doc/' + namespace,
    registry_namespace=legacy)


def doc_category_topics(namespace):
    """Finds all topics in given category."""
    test = operator.methodcaller('endswith', '.webdoc')
    return dict(
        map(lambda filename: (os.path.basename(filename)[:-7], filename),
            filter(test, doc_category(namespace))))
コード例 #18
0
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""Registries for search module."""

from flask_registry import RegistryError, ModuleAutoDiscoveryRegistry, \
    RegistryProxy
from werkzeug.utils import cached_property

from invenio.ext.registry import DictModuleAutoDiscoverySubRegistry, \
    ModuleAutoDiscoverySubRegistry
from invenio.modules.search.models import FacetCollection
from invenio.modules.search.facet_builders import FacetBuilder
from invenio.utils.memoise import memoize

searchext = RegistryProxy('searchext', ModuleAutoDiscoveryRegistry,
                          'searchext')


class SearchServiceRegistry(ModuleAutoDiscoverySubRegistry):

    """Search Service Registry."""

    __required_plugin_API_version__ = "Search Service Plugin API 1.0"

    def register(self, item):
        """Check plugin version and instantiate search service plugin."""
        if item.__plugin_version__ != self.__required_plugin_API_version__:
            raise RegistryError(
                'Invalid plugin version {0} required {1}'.format(
                    item.__plugin_version__,
                    self.__required_plugin_API_version__
コード例 #19
0
ファイル: registry.py プロジェクト: osub3/invenio
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""Registries for search module."""

from flask_registry import RegistryError, ModuleAutoDiscoveryRegistry, \
    RegistryProxy
from werkzeug.utils import cached_property

from invenio.ext.registry import DictModuleAutoDiscoverySubRegistry, \
    ModuleAutoDiscoverySubRegistry
from invenio.modules.collections.models import FacetCollection
from invenio.utils.memoise import memoize

searchext = RegistryProxy('searchext', ModuleAutoDiscoveryRegistry,
                          'searchext')


class SearchServiceRegistry(ModuleAutoDiscoverySubRegistry):

    """Search Service Registry."""

    __required_plugin_API_version__ = "Search Service Plugin API 1.0"

    def register(self, item):
        """Check plugin version and instantiate search service plugin."""
        if item.__plugin_version__ != self.__required_plugin_API_version__:
            raise RegistryError(
                'Invalid plugin version {0} required {1}'.format(
                    item.__plugin_version__,
                    self.__required_plugin_API_version__
コード例 #20
0
ファイル: registry.py プロジェクト: jalavik/invenio-records
def jsonext(namespace):
    return RegistryProxy(namespace, ModuleAutoDiscoveryRegistry, namespace)
コード例 #21
0
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

import os
import inspect

from flask import current_app
from flask_registry import RegistryProxy, ImportPathRegistry, \
    ModuleAutoDiscoveryRegistry

from invenio.ext.registry import ModuleAutoDiscoverySubRegistry
from invenio.utils.datastructures import LazyDict

legacy_modules = RegistryProxy('legacy', ImportPathRegistry,
                               initial=['invenio.legacy.*'])

webadmin_proxy = RegistryProxy('legacy.webadmin', \
        ModuleAutoDiscoverySubRegistry, 'web.admin',
        registry_namespace=legacy_modules)

def _admin_handler_name(name):
    parts = name.split('.')
    return '%s/%s' % (parts[2], parts[5])

webadmin = LazyDict(lambda: dict((_admin_handler_name(module.__name__), module)
                                 for module in webadmin_proxy))

webinterface_proxy = RegistryProxy(
    'legacy.webinterface', ModuleAutoDiscoveryRegistry, 'webinterface',
    registry_namespace=legacy_modules)
コード例 #22
0
        """No key mapping."""
        return key

    def _walk_dir(self, pkg, base, root):
        """Recursively register *.spec.js/*.js files."""
        for root, dirs, files in os.walk(root):
            for name in files:
                if JasmineSpecsAutoDiscoveryRegistry.pattern.match(name):
                    filename = os.path.join(root, name)
                    filepath = "{0}/{1}".format(pkg, filename[len(base) + 1:])
                    self.register(filename, key=filepath)

    def _discover_module(self, pkg):
        """Load list of files from resource directory."""
        import_str = pkg + '.' + self.module_name

        try:
            module = import_string(import_str, silent=self.silent)
            if module is not None:
                for p in module.__path__:
                    specsfolder = os.path.join(p, self.specs_folder)
                    if os.path.isdir(specsfolder):
                        self._walk_dir(pkg, specsfolder, specsfolder)
        except ImportError as e:  # pylint: disable=C0103
            self._handle_importerror(e, pkg, import_str)
        except SyntaxError as e:
            self._handle_syntaxerror(e, pkg, import_str)


specs = RegistryProxy("jasmine.specs", JasmineSpecsAutoDiscoveryRegistry)
コード例 #23
0
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Registries for search module."""

import os

from flask_registry import RegistryError, PkgResourcesDirDiscoveryRegistry, \
    ModuleAutoDiscoveryRegistry, RegistryProxy
from werkzeug.utils import cached_property

from invenio_ext.registry import DictModuleAutoDiscoverySubRegistry
from invenio.utils.datastructures import LazyDict
from invenio.utils.memoise import memoize

searchext = RegistryProxy('searchext', ModuleAutoDiscoveryRegistry,
                          'searchext')


class FacetsRegistry(DictModuleAutoDiscoverySubRegistry):
    """Registry for facets modules.

    Serves also modules sets and their configuration
    for specific collections.
    """
    def keygetter(self, key, original_value, new_value):
        """Compute the key for a value being registered.

        The key is the facet name stored in facet module.

        :param key: Key if provided by the user. Defaults to None.
        :param value: Value being registered. FacetBuilder object
コード例 #24
0
ファイル: registry.py プロジェクト: chokribr/invenio-1
        return class_.__name__ \
            if hasattr(class_, '__name__') and key is None else key

    def valuegetter(self, class_or_module):
        if inspect.ismodule(class_or_module):
            attr_name = class_or_module.__name__.split('.')[-1]
            if attr_name == '__init__':
                # Ignore __init__ modules.
                return None

            if hasattr(class_or_module, attr_name):
                #key = attr_name if key is None else key
                return getattr(class_or_module, attr_name)
            else:
                all_ = getattr(class_or_module, '__all__', [])
                if len(all_) == 0:
                    raise RegistryError(
                        "Workflow class not found. Class name must match "
                        "module name or be first element in  __all__. "
                        "Please check: {0}.{1}".format(class_or_module,
                                                       attr_name)
                    )
                return getattr(class_or_module, all_[0])
        return class_or_module


workflows = RegistryProxy('workflows', WorkflowsRegistry, 'workflows')
actions = RegistryProxy('workflows.actions', WorkflowsRegistry, 'actions')

__all__ = ['actions', 'workflows']
コード例 #25
0
import os

from flask_registry import (
    ModuleAutoDiscoveryRegistry,
    PkgResourcesDirDiscoveryRegistry,
    RegistryProxy,
)

from invenio_ext.registry import ModuleAutoDiscoverySubRegistry

from invenio_utils.datastructures import LazyDict

import yaml

format_templates_directories = RegistryProxy('format_templates_directories',
                                             ModuleAutoDiscoveryRegistry,
                                             'format_templates')

format_templates = RegistryProxy(
    'format_templates',
    PkgResourcesDirDiscoveryRegistry,
    '.',
    registry_namespace=format_templates_directories)

output_formats_directories = RegistryProxy('output_formats_directories',
                                           ModuleAutoDiscoveryRegistry,
                                           'output_formats')

output_formats_files = RegistryProxy(
    'output_formats_files',
    PkgResourcesDirDiscoveryRegistry,
コード例 #26
0
                # Autocommit cause Exception in SQLAlchemy >= 0.9.
                # @see http://docs.sqlalchemy.org/en/rel_0_9/
                #   core/connections.html#understanding-autocommit
                # 'autocommit': True,
                'use_unicode': False,
                'charset': 'utf8mb4',
            })
            event.listen(Pool, 'checkin', autocommit_on_checkin)


db = SQLAlchemy()
"""
    Provides access to :class:`~.SQLAlchemy` instance.
"""

models = RegistryProxy('models', ModuleAutoDiscoveryRegistry, 'models')


def setup_app(app):
    """Setup SQLAlchemy extension."""
    if 'SQLALCHEMY_DATABASE_URI' not in app.config:
        from sqlalchemy.engine.url import URL
        cfg = app.config

        app.config['SQLALCHEMY_DATABASE_URI'] = URL(
            cfg.get('CFG_DATABASE_TYPE', 'mysql'),
            username=cfg.get('CFG_DATABASE_USER'),
            password=cfg.get('CFG_DATABASE_PASS'),
            host=cfg.get('CFG_DATABASE_HOST'),
            database=cfg.get('CFG_DATABASE_NAME'),
            port=cfg.get('CFG_DATABASE_PORT'),
コード例 #27
0
ファイル: registry.py プロジェクト: chokribr/invenio-1
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""Registry definition for fixture datasets."""

from flask_registry import RegistryProxy

from invenio.ext.registry import ModuleAutoDiscoveryRegistry
from invenio.utils.datastructures import LazyDict


fixtures_proxy = RegistryProxy(
    'fixtures', ModuleAutoDiscoveryRegistry, 'fixtures')


def fixtures_loader():
    """Load fixtures datasets."""
    out = {}
    for fixture in fixtures_proxy:
        for data in getattr(fixture, '__all__', dir(fixture)):
            if data[-4:] != 'Data' or data in out:
                continue
            out[data] = getattr(fixture, data)
    return out

fixtures = LazyDict(fixtures_loader)
コード例 #28
0
import click
from flask_cli import with_appcontext
from flask_sqlalchemy import SQLAlchemy
#from flask_migrate import Migrate
from flask_registry import ModuleAutoDiscoveryRegistry, RegistryProxy
from flask import current_app

db = SQLAlchemy()
#migrate = Migrate()

models = RegistryProxy(
    'models',  # Registry namespace
    ModuleAutoDiscoveryRegistry,
    'models'  # Module name (i.e. models.py)
)

from mods.api.models import Client, Eval, File, EvalFiles


def setup_app(app):
    # Set default configuration
    # Add extension CLI to application.
    app.cli.add_command(initdb)
    app.cli.add_command(initdemo)
    db.init_app(app)
    #migrate.init_app(app, db)


@click.command()
@with_appcontext
def initdb():
コード例 #29
0
ファイル: registry.py プロジェクト: chokribr/invenio-1
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2014, 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

from flask_registry import ModuleAutoDiscoveryRegistry, RegistryProxy

tasks = RegistryProxy('tasks', ModuleAutoDiscoveryRegistry, 'tasks')
コード例 #30
0
ファイル: registry.py プロジェクト: chokribr/invenio-1
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

import os

from flask_registry import PkgResourcesDirDiscoveryRegistry, \
    ModuleAutoDiscoveryRegistry, RegistryProxy
from invenio.utils.datastructures import LazyDict

rankext = RegistryProxy('rankext', ModuleAutoDiscoveryRegistry, 'rankext')

configuration_proxy = RegistryProxy('rankext.configuration',
                                    PkgResourcesDirDiscoveryRegistry,
                                    'configuration',
                                    registry_namespace=rankext)

configuration = LazyDict(lambda: dict(
    (os.path.basename(f), f) for f in configuration_proxy))
コード例 #31
0
#
# This file is part of Invenio.
# Copyright (C) 2013, 2014, 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA

import pkg_resources

from flask_registry import ModuleAutoDiscoveryRegistry, RegistryProxy
from invenio.utils.datastructures import LazyDict

bulletinext = RegistryProxy('bulletinext', ModuleAutoDiscoveryRegistry,
                            'bulletinext')

journals = LazyDict(lambda: dict(
    (f, pkg_resources.resource_filename(l.__name__, f)) for l in bulletinext
    for f in pkg_resources.resource_listdir(l.__name__, '.')
    if pkg_resources.resource_isdir(l.__name__, f)))