def setup_config(config):
    app_abspath = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    app_config = Config(app_abspath)
    app_config.from_object("superdesk.default_settings")

    update_config(app_config)

    app_config.update(
        config or {},
        **{
            "APP_ABSPATH": app_abspath,
            "DEBUG": True,
            "TESTING": True,
        },
    )

    logging.getLogger("apps").setLevel(logging.WARNING)
    logging.getLogger("elastic").setLevel(logging.WARNING)  # elastic datalayer
    logging.getLogger("urllib3").setLevel(logging.WARNING)
    logging.getLogger("celery").setLevel(logging.WARNING)
    logging.getLogger("superdesk").setLevel(logging.ERROR)
    logging.getLogger("elasticsearch").setLevel(logging.ERROR)
    logging.getLogger("superdesk.errors").setLevel(logging.CRITICAL)

    return {key: deepcopy(val) for key, val in app_config.items()}
Exemple #2
0
def setup_config(config):
    app_abspath = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    app_config = Config(app_abspath)
    app_config.from_object("superdesk.default_settings")
    cwd = Path.cwd()
    for p in [cwd] + list(cwd.parents):
        settings = p / "settings.py"
        if settings.is_file():
            logger.info(f"using local settings from {settings}")
            app_config.from_pyfile(settings)
            break
    else:
        logger.warning("Can't find local settings")

    update_config(app_config)

    app_config.update(
        config or {},
        **{
            "APP_ABSPATH": app_abspath,
            "DEBUG": True,
            "TESTING": True,
        },
    )

    logging.getLogger("apps").setLevel(logging.WARNING)
    logging.getLogger("elastic").setLevel(logging.WARNING)  # elastic datalayer
    logging.getLogger("urllib3").setLevel(logging.WARNING)
    logging.getLogger("celery").setLevel(logging.WARNING)
    logging.getLogger("superdesk").setLevel(logging.ERROR)
    logging.getLogger("elasticsearch").setLevel(logging.ERROR)
    logging.getLogger("superdesk.errors").setLevel(logging.CRITICAL)

    return {key: deepcopy(val) for key, val in app_config.items()}
Exemple #3
0
def create_app(config_file=None, **kwargs):
    """
    Create a new eve app object and initialize everything.

    User configuration can be loaded in the following order:

    1. Use the `config_file` arg to specify a file
    2. If `config_file` is `None`, you set the environment variable
       `AMIVAPI_CONFIG` to the path of your config file
    3. If no environment variable is set either, `config.py` in the current
       working directory is used

    Args:
        config (path): Specify config file to use.
        kwargs: All other key-value arguments will be used to update the config
    Returns:
        (Eve): The Eve application
    """
    # Load config
    config = Config(getcwd())
    config.from_object("amivapi.settings")

    # Specified path > environment var > default path; abspath for better log
    user_config = abspath(config_file or getenv('AMIVAPI_CONFIG', 'config.py'))
    try:
        config.from_pyfile(user_config)
        config_status = "Config loaded: %s" % user_config
    except IOError:
        config_status = "No config found."

    config.update(kwargs)

    app = Eve(settings=config, validator=ValidatorAMIV)
    app.logger.info(config_status)

    # Set up error logging with sentry
    init_sentry(app)

    # Create LDAP connector
    ldap.init_app(app)

    # Initialize modules to register resources, validation, hooks, auth, etc.
    users.init_app(app)
    auth.init_app(app)
    events.init_app(app)
    groups.init_app(app)
    joboffers.init_app(app)
    beverages.init_app(app)
    studydocs.init_app(app)
    cascade.init_app(app)
    cron.init_app(app)
    documentation.init_app(app)

    # Fix that eve doesn't run hooks on embedded documents
    app.on_fetched_item += utils.run_embedded_hooks_fetched_item
    app.on_fetched_resource += utils.run_embedded_hooks_fetched_resource

    return app
Exemple #4
0
def create_app(config_file=None, **kwargs):
    """Create a new eve app object and initialize everything.

    User configuration can be loaded in the following order:

    1. Use the `config_file` arg to specify a file
    2. If `config_file` is `None`, you set the environment variable
       `PVK_CONFIG` to the path of your config file
    3. If no environment variable is set either, `config.py` in the current
       working directory is used

    Args:
        config (path): Specify config file to use.
        kwargs: All other key-value arguments will be used to update the config
    Returns:
        (Eve): The Eve application
    """
    # Load config
    config = Config(getcwd())
    config.from_object("backend.settings")

    # Specified path > environment var > default path; abspath for better log
    user_config = abspath(config_file or getenv('PVK_CONFIG', 'config.py'))
    try:
        config.from_pyfile(user_config)
        config_status = "Config loaded: %s" % user_config
    except IOError:
        config_status = "No config found."

    config.update(kwargs)

    # Create the app object
    application = Eve(auth=APIAuth, validator=APIValidator, settings=config)
    application.logger.info(config_status)

    # Eve provides hooks at several points of the request,
    # we use this do add dynamic filtering
    for resource in ['signups', 'selections']:
        for method in ['GET', 'PATCH', 'DELETE']:
            event = getattr(application, 'on_pre_%s_%s' % (method, resource))
            event += only_own_nethz

    # Also use hooks to add pre- and postprocessing to resources
    application.on_post_POST_signups += new_signups
    application.on_deleted_item_signups += deleted_signup
    application.on_updated_signups += patched_signup

    application.on_updated_courses += patched_course
    application.on_delete_item_courses += block_course_deletion

    application.on_insert_payments += create_payment
    application.on_inserted_payments += mark_as_paid
    application.on_deleted_item_payments += mark_as_unpaid

    return application
Exemple #5
0
def setup_config(config):
    app_abspath = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    app_config = Config(app_abspath)
    app_config.from_object('superdesk.default_settings')

    update_config(app_config)
    app_config.update(config or {}, **{
        'APP_ABSPATH': app_abspath,
        'DEBUG': True,
        'TESTING': True,
    })

    logging.getLogger('superdesk').setLevel(logging.WARNING)
    logging.getLogger('elastic').setLevel(logging.WARNING)  # elastic datalayer
    logging.getLogger('elasticsearch').setLevel(logging.WARNING)
    logging.getLogger('urllib3').setLevel(logging.WARNING)
    return app_config
class ConfigurationRegistry(ModuleDiscoveryRegistry):
    """
    Specialized ``ModuleDiscoveryRegistry`` that search for ``config`` modules
    in a list of Python packages and merge them into the Flask application
    config without overwriting already set variables.

    :param app: A Flask application
    :param registry_namespace: The registry namespace of an
        ``ImportPathRegistry`` with a list Python packages to search for
        ``config`` modules in. Defaults to ``packages``.
    """
    def __init__(self, app, registry_namespace=None):
        super(ConfigurationRegistry, self).__init__(
            'config',
            registry_namespace=registry_namespace,
            with_setup=False,
        )

        # Create a new configuration module to collect configuration in.
        from flask import Config
        self.new_config = Config(app.config.root_path)

        # Auto-discover configuration in packages
        self.discover(app)

        # Overwrite default configuration with user specified configuration
        self.new_config.update(app.config)
        app.config = self.new_config

    def register(self, new_object):
        """
        Register a new ``config`` module.

        :param new_object: The configuration module.
            ``app.config.from_object()`` will be called on it.
        """
        self.new_config.from_object(new_object)
        super(ConfigurationRegistry, self).register(new_object)

    def unregister(self, *args, **kwargs):
        """
        It is not possible to unregister configuration.
        """
        raise NotImplementedError()
Exemple #7
0
def setup_config(config):
    app_abspath = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    app_config = Config(app_abspath)
    app_config.from_object("superdesk.default_settings")
    cwd = Path.cwd()
    for p in [cwd] + list(cwd.parents):
        settings = p / "settings.py"
        if settings.is_file():
            logger.info(f"using local settings from {settings}")
            app_config.from_pyfile(settings)
            break
    else:
        logger.warning("Can't find local settings")

    update_config(app_config)

    app_config.setdefault("INSTALLED_APPS", [])

    # Extend the INSTALLED APPS with the list provided
    if config:
        config.setdefault("INSTALLED_APPS", [])
        app_config["INSTALLED_APPS"].extend(config.pop("INSTALLED_APPS", []))

    # Make sure there are no duplicate entries in INSTALLED_APPS
    app_config["INSTALLED_APPS"] = list(set(app_config["INSTALLED_APPS"]))

    app_config.update(
        config or {},
        **{
            "APP_ABSPATH": app_abspath,
            "DEBUG": True,
            "TESTING": True,
        },
    )

    logging.getLogger("apps").setLevel(logging.WARNING)
    logging.getLogger("elastic").setLevel(logging.WARNING)  # elastic datalayer
    logging.getLogger("urllib3").setLevel(logging.WARNING)
    logging.getLogger("celery").setLevel(logging.WARNING)
    logging.getLogger("superdesk").setLevel(logging.ERROR)
    logging.getLogger("elasticsearch").setLevel(logging.ERROR)
    logging.getLogger("superdesk.errors").setLevel(logging.CRITICAL)

    return {key: deepcopy(val) for key, val in app_config.items()}
class ConfigurationRegistry(ModuleDiscoveryRegistry):
    """
    Specialized ``ModuleDiscoveryRegistry`` that search for ``config`` modules
    in a list of Python packages and merge them into the Flask application
    config without overwriting already set variables.

    :param app: A Flask application
    :param registry_namespace: The registry namespace of an
        ``ImportPathRegistry`` with a list Python packages to search for
        ``config`` modules in. Defaults to ``packages``.
    """
    def __init__(self, app, registry_namespace=None):
        super(ConfigurationRegistry, self).__init__(
            'config',
            registry_namespace=registry_namespace,
            with_setup=False,
        )

        # Create a new configuration module to collect configuration in.
        self.new_config = Config(app.config.root_path)

        # Auto-discover configuration in packages
        self.discover(app)

        # Overwrite default configuration with user specified configuration
        self.new_config.update(app.config)
        app.config.update(self.new_config)

    def register(self, new_object):
        """
        Register a new ``config`` module.

        :param new_object: The configuration module.
            ``app.config.from_object()`` will be called on it.
        """
        self.new_config.from_object(new_object)
        super(ConfigurationRegistry, self).register(new_object)

    def unregister(self, *args, **kwargs):
        """
        It is not possible to unregister configuration.
        """
        raise NotImplementedError()
Exemple #9
0
def setup_config(config):
    app_abspath = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    app_config = Config(app_abspath)
    app_config.from_object('superdesk.default_settings')

    update_config(app_config)
    app_config.update(config or {}, **{
        'APP_ABSPATH': app_abspath,
        'DEBUG': True,
        'TESTING': True,
    })

    logging.getLogger('apps').setLevel(logging.WARNING)
    logging.getLogger('elastic').setLevel(logging.WARNING)  # elastic datalayer
    logging.getLogger('urllib3').setLevel(logging.WARNING)
    logging.getLogger('celery').setLevel(logging.WARNING)
    logging.getLogger('superdesk').setLevel(logging.ERROR)
    logging.getLogger('elasticsearch').setLevel(logging.ERROR)
    return app_config
Exemple #10
0
def setup(context=None, config=None, app_factory=get_app):

    app_abspath = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    app_config = Config(app_abspath)
    app_config.from_object('superdesk.tests.test_settings')
    app_config['APP_ABSPATH'] = app_abspath

    app_config.update(get_test_settings())
    app_config.update(config or {})

    app_config.update({
        'DEBUG': True,
        'TESTING': True,
    })

    app = app_factory(app_config)
    logger = logging.getLogger('superdesk')
    logger.setLevel(logging.ERROR)
    logger = logging.getLogger('elasticsearch')
    logger.setLevel(logging.ERROR)
    logger = logging.getLogger('urllib3')
    logger.setLevel(logging.ERROR)
    drop_elastic(app)
    drop_mongo(app)

    # create index again after dropping it
    app.data.init_elastic(app)

    if context:
        context.app = app
        context.client = app.test_client()
Exemple #11
0
def setup(context=None, config=None, app_factory=get_app):

    app_abspath = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    app_config = Config(app_abspath)
    app_config.from_object('superdesk.tests.test_settings')
    app_config['APP_ABSPATH'] = app_abspath

    app_config.update(get_test_settings())
    app_config.update(config or {})

    app_config.update({
        'DEBUG': True,
        'TESTING': True,
    })

    app = app_factory(app_config)
    logger = logging.getLogger('superdesk')
    logger.setLevel(logging.ERROR)
    logger = logging.getLogger('elasticsearch')
    logger.setLevel(logging.ERROR)
    logger = logging.getLogger('urllib3')
    logger.setLevel(logging.ERROR)
    drop_elastic(app)
    drop_mongo(app)

    # create index again after dropping it
    app.data.init_elastic(app)

    if context:
        context.app = app
        context.client = app.test_client()
class ConfigurationRegistry(ModuleDiscoveryRegistry):
    """
    Specialized import path registry that takes the initial list of import
    paths from ``PACKAGES`` configuration variable.

    Example::

        app.extensions['registry']['packages'] = PackageRegistry()
        app.extendsions['registry']['config'] = ConfigurationRegistry(
            _app, base_config='invenio.core.config'
        )
    """
    def __init__(self, app, registry_namespace=None):
        super(ConfigurationRegistry, self).__init__(
            'config',
            registry_namespace=registry_namespace,
            with_setup=False,
        )

        # Create a new configuration module to collect configuration in.
        from flask import Config
        self.new_config = Config(app.config.root_path)

        # Auto-discover configuration in packages
        self.discover(app)

        # Overwrite default configuration with user specified configuration
        self.new_config.update(app.config)
        app.config = self.new_config

    def register(self, new_object):
        self.new_config.from_object(new_object)
        super(ConfigurationRegistry, self).register(new_object)

    def unregister(self, *args, **kwargs):
        raise NotImplementedError()
Exemple #13
0
def setup_config(config):
    app_abspath = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    app_config = Config(app_abspath)
    app_config.from_object('superdesk.tests.test_settings')
    app_config['APP_ABSPATH'] = app_abspath

    app_config.update(get_test_settings())
    app_config.update(config or {})

    app_config.update({
        'DEBUG': True,
        'TESTING': True,
    })

    logging.getLogger('superdesk').setLevel(logging.WARNING)
    logging.getLogger('elastic').setLevel(logging.WARNING)  # elastic datalayer
    logging.getLogger('elasticsearch').setLevel(logging.WARNING)
    logging.getLogger('urllib3').setLevel(logging.WARNING)
    return app_config
Exemple #14
0
def create_app(config_file=None, **kwargs):
    """
    Create a new eve app object and initialize everything.

    User configuration can be loaded in the following order:

    1. Use the `config_file` arg to specify a file
    2. If `config_file` is `None`, you set the environment variable
       `AMIVAPI_CONFIG` to the path of your config file
    3. If no environment variable is set either, `config.py` in the current
       working directory is used

    Args:
        config (path): Specify config file to use.
        kwargs: All other key-value arguments will be used to update the config
    Returns:
        (Eve): The Eve application
    """
    # Load config
    config = Config(getcwd())
    config.from_object("amivapi.settings")

    # Specified path > environment var > default path; abspath for better log
    user_config = abspath(config_file or getenv('AMIVAPI_CONFIG', 'config.py'))
    try:
        config.from_pyfile(user_config)
        config_status = "Config loaded: %s" % user_config
    except IOError:
        config_status = "No config found."

    config.update(kwargs)

    # Initialize empty domain to create Eve object, register resources later
    config['DOMAIN'] = {}

    app = Eve("amivapi",  # Flask needs this name to find the static folder
              settings=config,
              validator=ValidatorAMIV)
    app.logger.info(config_status)

    # Set up error logging with sentry
    init_sentry(app)

    # Create LDAP connector
    ldap.init_app(app)

    # Initialize modules to register resources, validation, hooks, auth, etc.
    users.init_app(app)
    auth.init_app(app)
    events.init_app(app)
    groups.init_app(app)
    blacklist.init_app(app)
    joboffers.init_app(app)
    beverages.init_app(app)
    studydocs.init_app(app)
    cascade.init_app(app)
    cron.init_app(app)
    documentation.init_app(app)

    # Fix that eve doesn't run hooks on embedded documents
    app.on_fetched_item += utils.run_embedded_hooks_fetched_item
    app.on_fetched_resource += utils.run_embedded_hooks_fetched_resource

    return app