Exemplo n.º 1
0
def load_application(app):
    """Load the application.

    Assembles the application by use of ``PACKAGES`` and ``EXTENSIONS``
    configuration variables.

    1. Load extensions by calling ``setup_app()`` in module defined in
       ``EXTENSIONS``.
    2. Register blueprints from each module defined in ``PACAKGES`` by looking
       searching in ``views.py`` for a ``blueprint`` or ``blueprints``
       variable.

    :param app: Flask application.
    """
    # Extend application config with default configuration values from packages
    # (app config takes precedence)
    app.extensions['registry'].update(
        # Register extensions listed in EXTENSIONS conf variable.
        extensions=ExtensionRegistry(app),
        # Register blueprints from packages in PACKAGES configuration variable.
        blueprints=BlueprintAutoDiscoveryRegistry(app=app),
    )

    ConfigurationRegistry(app)

    app.extensions['loaded'] = True
Exemplo n.º 2
0
def create_app(config):
    app = Flask('myapp')
    app.config.from_object(config)
    r = Registry(app=app)
    r['packages'] = PackageRegistry(app)
    r['extensions'] = ExtensionRegistry(app)
    r['config'] = ConfigurationRegistry(app)
    r['blueprints'] = BlueprintAutoDiscoveryRegistry(app=app)
    return app
Exemplo n.º 3
0
    def test_import_error(self):
        Registry(app=self.app)

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

        self.app.extensions['registry']['blueprints'] = \
            BlueprintAutoDiscoveryRegistry(app=self.app)

        self.assertEqual(len(self.app.extensions['registry']['blueprints']), 0)
Exemplo n.º 4
0
    def test_registration(self):
        Registry(app=self.app)

        self.app.extensions['registry']['packages'] = \
            ImportPathRegistry(initial=['registry_module'])

        self.app.extensions['registry']['blueprints'] = \
            BlueprintAutoDiscoveryRegistry(app=self.app)

        self.assertEqual(
            len(self.app.extensions['registry']['blueprints']),
            3
        )
Exemplo n.º 5
0
    def test_syntax_error(self):
        Registry(app=self.app)

        self.app.extensions['registry']['packages'] = \
            ImportPathRegistry(initial=['tests'])

        self.assertRaises(SyntaxError,
                          BlueprintAutoDiscoveryRegistry,
                          app=self.app,
                          module_name='syntaxerror_views')

        self.app.extensions['registry'].update(
            blueprints=BlueprintAutoDiscoveryRegistry(
                app=self.app, module_name='syntaxerror_views', silent=True))

        self.assertEqual(len(self.app.extensions['registry']['blueprints']), 0)
Exemplo n.º 6
0
def se_leg_rp_init_app(name, config):
    """
    Create an instance of an se_leg_rp app.

    First, it will load the configuration from settings.common, settings.dev then any settings
    given in the `config` param.

    :param name: The name of the instance, it will affect the configuration loaded.
    :param config: any additional configuration settings. Specially useful
                   in test cases

    :type name: str
    :type config: dict

    :return: the flask app
    :rtype: flask.Flask
    """

    app = Flask(name)

    app.config.from_object('se_leg_rp.settings.common')
    app.config.from_envvar(SE_LEG_RP_SETTINGS_ENVVAR, silent=False)
    app.config.update(config)

    # Initialize helpers
    app.wsgi_app = ProxyFix(app.wsgi_app)
    app = init_exception_handlers(app)
    app = init_logging(app)
    r = Registry(app=app)
    r['packages'] = PackageRegistry(app)
    r['extensions'] = ExtensionRegistry(app)
    r['config'] = ConfigurationRegistry(app)
    r['blueprints'] = BlueprintAutoDiscoveryRegistry(app=app)

    from .views import rp_views
    app.register_blueprint(rp_views)

    # Initialize the oidc_client after views to be able to set correct redirect_uris
    app = init_oidc_client(app)

    # Initialize db
    app.proofing_statedb = OidcProofingStateDB(app.config['MONGO_URI'])
    app.proofdb = ProofDB(app.config['MONGO_URI'])

    app.logger.info('Started {!s}'.format(name))

    return app
Exemplo n.º 7
0
def create_app(instance_path="", env="prod"):
    """Create the app."""
    app_name = '.'.join(__name__.split('.')[0:2])

    instance_path = instance_path or os.path.join(sys.prefix, 'var',
                                                  app_name + '-instance')
    try:
        if not os.path.exists(instance_path):
            os.makedirs(instance_path)
    except Exception:
        pass

    app = Flask(
        app_name,
        instance_path=instance_path,
        instance_relative_config=True,
        static_folder=os.path.join(instance_path, 'static'),
    )

    app.config['ENV'] = env
    env_object = "iiif.base.config.{0}Config".format(env.capitalize())
    app.config.from_object(env_object)
    app.config.from_envvar('iiif_ENV_SRC', silent=True)
    app.config.from_pyfile('application.cfg', silent=True)

    # Ignore slashes
    app.url_map.strict_slashes = False

    # Add the proxies
    Registry(app=app)
    app.extensions['registry'].update(packages=PackageRegistry(app))
    app.extensions['registry'].update(
        extensions=ExtensionRegistry(app),
        blueprints=BlueprintAutoDiscoveryRegistry(app=app),
    )
    ConfigurationRegistry(app)
    _setup_app_errors(app)
    return app
Exemplo n.º 8
0
def create_app(instance_path=None, **kwargs_config):
    """Prepare Invenio application based on Flask.

    Invenio consists of a new Flask application with legacy support for
    the old WSGI legacy application and the old Python legacy
    scripts (URLs to ``*.py`` files).
    """
    configure_warnings()

    # Flask application name
    app_name = '.'.join(__name__.split('.')[0:2])

    # Force instance folder to always be located in under system prefix
    instance_path = instance_path or os.path.join(sys.prefix, 'var',
                                                  app_name + '-instance')

    # Create instance path
    try:
        if not os.path.exists(instance_path):
            os.makedirs(instance_path)
    except Exception:
        pass

    # Create the Flask application instance
    app = Flask(
        app_name,
        # Static files are usually handled directly by the webserver (e.g.
        # Apache) However in case WSGI is required to handle static files too
        # (such as when running simple server), then this flag can be
        # turned on (it is done automatically by wsgi_handler_test).
        # We assume anything under '/' which is static to be server directly
        # by the webserver from CFG_WEBDIR. In order to generate independent
        # url for static files use func:`url_for('static', filename='test')`.
        static_url_path='',
        static_folder=os.path.join(instance_path, 'static'),
        template_folder='templates',
        instance_relative_config=True,
        instance_path=instance_path,
    )

    # Handle both URLs with and without trailing slashes by Flask.
    # @blueprint.route('/test')
    # @blueprint.route('/test/') -> not necessary when strict_slashes == False
    app.url_map.strict_slashes = False

    #
    # Configuration loading
    #

    # Load default configuration
    app.config.from_object('invenio.base.config')

    # Load site specific default configuration from entry points
    load_site_config(app)

    # Load invenio.cfg from instance folder
    app.config.from_pyfile('invenio.cfg', silent=True)

    # Update application config from parameters.
    app.config.update(kwargs_config)

    # Ensure SECRET_KEY has a value in the application configuration
    register_secret_key(app)

    # Update config with specified environment variables.
    for cfg_name in app.config.get(
            'INVENIO_APP_CONFIG_ENVS',
            os.getenv('INVENIO_APP_CONFIG_ENVS', '').split(',')):
        cfg_name = cfg_name.strip().upper()
        if cfg_name:
            cfg_value = app.config.get(cfg_name)
            cfg_value = os.getenv(cfg_name, cfg_value)
            try:
                cfg_value = ast.literal_eval(cfg_value)
            except (SyntaxError, ValueError):
                pass
            app.config[cfg_name] = cfg_value
            app.logger.debug("{0} = {1}".format(cfg_name, cfg_value))

    # ====================
    # Application assembly
    # ====================
    # Initialize application registry, used for discovery and loading of
    # configuration, extensions and Invenio packages
    Registry(app=app)

    app.extensions['registry'].update(
        # Register packages listed in invenio.cfg
        packages=PackageRegistry(app))

    app.extensions['registry'].update(
        # Register extensions listed in invenio.cfg
        extensions=ExtensionRegistry(app),
        # Register blueprints
        blueprints=BlueprintAutoDiscoveryRegistry(app=app),
    )

    # Extend application config with configuration from packages (app config
    # takes precedence)
    ConfigurationRegistry(app)

    # Legacy conf cleanup
    cleanup_legacy_configuration(app)

    register_legacy_blueprints(app)

    return app
Exemplo n.º 9
0
def create_app(app_name=None,
               instance_path=None,
               static_path=None,
               static_folder=None,
               **config):
    """Returns a :class:`Flask` application instance configured with common
    functionality for the AdsWS platform.

    :param app_name: application package name
    :param instance_path: application package path
    :param static_path: flask.Flask static_path kwarg
    :param static_folder: flask.Flask static_folder kwarg
    :param config: a dictionary of settings to override
    """
    # Flask application name
    app_name = app_name or '.'.join(__name__.split('.')[0:-1])

    # Force instance folder to always be located one level above adsws
    instance_path = instance_path or os.path.realpath(
        os.path.join(os.path.dirname(__file__), '../instance'))

    # Create instance path
    try:
        if not os.path.exists(instance_path):
            os.makedirs(instance_path)
    except:
        pass

    app = ADSFlask(app_name,
                   instance_path=instance_path,
                   instance_relative_config=False,
                   static_path=static_path,
                   static_folder=static_folder,
                   local_config=config or {})

    # Handle both URLs with and without trailing slashes by Flask.
    app.url_map.strict_slashes = False

    load_config(app, config)

    # Ensure SECRET_KEY has a value in the application configuration
    register_secret_key(app)

    # ====================
    # Application assembly
    # ====================
    # Initialize application registry, used for discovery and loading of
    # configuration, extensions and Invenio packages
    Registry(app=app)

    app.extensions['registry'].update(
        # Register packages listed in config
        packages=PackageRegistry(app))

    app.extensions['registry'].update(
        # Register extensions listed in config
        extensions=ExtensionRegistry(app),
        # Register blueprints
        blueprints=BlueprintAutoDiscoveryRegistry(app=app),
    )

    # Extend application config with configuration from packages (app config
    # takes precedence)
    ConfigurationRegistry(app)

    configure_a_more_verbose_log_exception(app)

    app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)

    app.before_request(set_translations)
    app.before_request(make_session_permanent)
    app.before_request(cache_data_stream)

    if app.config.get('PRODUCTION', False):
        app.wsgi_app = ProxyFix(app.wsgi_app,
                                num_proxies=app.config.get('NUM_PROXIES', 2))

    if app.config.get('HTTPS_ONLY', False):
        # Contains the x-forwarded-proto in the criteria already
        # only works if app.debug=False
        # permanent=True responds with 302 instead of 301
        SSLify(app, permanent=True)

    # Register custom error handlers
    if not app.config.get('DEBUG'):
        app.errorhandler(404)(on_404)
        app.errorhandler(401)(on_401)
        app.errorhandler(429)(on_429)
        app.errorhandler(405)(on_405)

    @oauth2.after_request
    def set_adsws_uid_header(valid, oauth):
        """
        If the user is authenticated, inject the header "X-adsws-uid" into
        the incoming request header
        """
        h = Headers(request.headers.items())

        if current_user.is_authenticated():
            h.add_header("X-Adsws-Uid", current_user.id)

        if valid:
            level = oauth.client.ratelimit
            if level is None:
                level = 1.0
            h.add_header("X-Adsws-Ratelimit-Level", level)
        else:
            h.add_header("X-Adsws-Ratelimit-Level", 0.0)

        request.headers = h
        return valid, oauth

    @app.teardown_request
    def teardown_request(exception=None):
        """This function will close active transaction, if there is one
        but only if the session is not dirty - we don't want to do any
        magic (instead of a developer)
        
        use expire_on_commit=False doesn't have the same effect
        http://docs.sqlalchemy.org/en/latest/orm/session_api.html#sqlalchemy.orm.session.Session.commit
        
        The problems we are facing is that a new transaction gets opened
        when session is committed; consequent access to the ORM objects
        opens a new transaction (which never gets closed and is rolled back)
        """
        a = current_app
        if 'sqlalchemy' in a.extensions:  # could use self.db but let's be very careful
            sa = a.extensions['sqlalchemy']
            if hasattr(sa, 'db') and hasattr(
                    sa.db, 'session') and sa.db.session.is_active:
                if bool(sa.db.session.dirty):
                    sa.db.session.close()  # db server will do rollback
                else:
                    sa.db.session.commit()  # normal situation

    return app
Exemplo n.º 10
0
def create_app(app_name=None,
               instance_path=None,
               static_path=None,
               static_folder=None,
               **config):
    """Returns a :class:`Flask` application instance configured with common
    functionality for the AdsWS platform.

    :param app_name: application package name
    :param instance_path: application package path
    :param static_path: flask.Flask static_path kwarg
    :param static_folder: flask.Flask static_folder kwarg
    :param config: a dictionary of settings to override
    """
    # Flask application name
    app_name = app_name or '.'.join(__name__.split('.')[0:-1])

    # Force instance folder to always be located one level above adsws
    instance_path = instance_path or os.path.realpath(
        os.path.join(os.path.dirname(__file__), '../instance'))

    # Create instance path
    try:
        if not os.path.exists(instance_path):
            os.makedirs(instance_path)
    except:
        pass

    app = ADSFlask(app_name,
                   instance_path=instance_path,
                   instance_relative_config=False,
                   static_path=static_path,
                   static_folder=static_folder,
                   local_config=config or {})

    # Handle both URLs with and without trailing slashes by Flask.
    app.url_map.strict_slashes = False

    load_config(app, config)

    # Ensure SECRET_KEY has a value in the application configuration
    register_secret_key(app)

    # ====================
    # Application assembly
    # ====================
    # Initialize application registry, used for discovery and loading of
    # configuration, extensions and Invenio packages
    Registry(app=app)

    app.extensions['registry'].update(
        # Register packages listed in config
        packages=PackageRegistry(app))

    app.extensions['registry'].update(
        # Register extensions listed in config
        extensions=ExtensionRegistry(app),
        # Register blueprints
        blueprints=BlueprintAutoDiscoveryRegistry(app=app),
    )

    # Extend application config with configuration from packages (app config
    # takes precedence)
    ConfigurationRegistry(app)

    configure_a_more_verbose_log_exception(app)

    app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)

    app.before_request(set_translations)
    app.before_request(make_session_permanent)

    if app.config.get('PRODUCTION', False):
        app.wsgi_app = ProxyFix(app.wsgi_app,
                                num_proxies=app.config.get('NUM_PROXIES', 2))

    if app.config.get('HTTPS_ONLY', False):
        # Contains the x-forwarded-proto in the criteria already
        # only works if app.debug=False
        # permanent=True responds with 302 instead of 301
        SSLify(app, permanent=True)

    # Register custom error handlers
    if not app.config.get('DEBUG'):
        app.errorhandler(404)(on_404)
        app.errorhandler(401)(on_401)
        app.errorhandler(429)(on_429)
        app.errorhandler(405)(on_405)

    @oauth2.after_request
    def set_adsws_uid_header(valid, oauth):
        """
        If the user is authenticated, inject the header "X-adsws-uid" into
        the incoming request header
        """
        if current_user.is_authenticated():
            h = Headers(request.headers.items())
            h.add_header("X-Adsws-Uid", current_user.id)
            if current_user.ratelimit_level is not None:
                h.add_header("X-Adsws-Ratelimit-Level",
                             current_user.ratelimit_level)
            request.headers = h
        return valid, oauth

    return app