Do setup that requires a Flask app.

        :param app: The application to initialize.
        :type app: Flask
505795
def init_app(self, app):
        
        secrets = self.load_secrets(app)
        self.client_secrets = list(secrets.values())[0]
        secrets_cache = DummySecretsCache(secrets)

        # Set some default configuration options
        app.config.setdefault('OIDC_SCOPES', ['openid', 'email'])
        app.config.setdefault('OIDC_GOOGLE_APPS_DOMAIN', None)
        app.config.setdefault('OIDC_ID_TOKEN_COOKIE_NAME', 'oidc_id_token')
        app.config.setdefault('OIDC_ID_TOKEN_COOKIE_PATH', '/')
        app.config.setdefault('OIDC_ID_TOKEN_COOKIE_TTL', 7 * 86400)  # 7 days
        # should ONLY be turned off for local debugging
        app.config.setdefault('OIDC_COOKIE_SECURE', True)
        app.config.setdefault('OIDC_VALID_ISSUERS',
                              (self.client_secrets.get('issuer') or
                               GOOGLE_ISSUERS))
        app.config.setdefault('OIDC_CLOCK_SKEW', 60)  # 1 minute
        app.config.setdefault('OIDC_REQUIRE_VERIFIED_EMAIL', False)
        app.config.setdefault('OIDC_OPENID_REALM', None)
        app.config.setdefault('OIDC_USER_INFO_ENABLED', True)
        app.config.setdefault('OIDC_CALLBACK_ROUTE', '/oidc_callback')
        app.config.setdefault('OVERWRITE_REDIRECT_URI', False)
        app.config.setdefault("OIDC_EXTRA_REQUEST_AUTH_PARAMS", {})
        # Configuration for resource servers
        app.config.setdefault('OIDC_RESOURCE_SERVER_ONLY', False)
        app.config.setdefault('OIDC_RESOURCE_CHECK_AUD', False)

        # We use client_secret_post, because that's what the Google
        # oauth2client library defaults to
        app.config.setdefault('OIDC_INTROSPECTION_AUTH_METHOD', 'client_secret_post')
        app.config.setdefault('OIDC_TOKEN_TYPE_HINT', 'access_token')

        if not 'openid' in app.config['OIDC_SCOPES']:
            raise ValueError('The value "openid" must be in the OIDC_SCOPES')

        # register callback route and cookie-setting decorator
        if not app.config['OIDC_RESOURCE_SERVER_ONLY']:
            app.route(app.config['OIDC_CALLBACK_ROUTE'])(self._oidc_callback)
            app.before_request(self._before_request)
            app.after_request(self._after_request)

        # Initialize oauth2client
        self.flow = flow_from_clientsecrets(
            app.config['OIDC_CLIENT_SECRETS'],
            scope=app.config['OIDC_SCOPES'],
            cache=secrets_cache)
        assert isinstance(self.flow, OAuth2WebServerFlow)

        # create signers using the Flask secret key
        self.extra_data_serializer = JSONWebSignatureSerializer(
            app.config['SECRET_KEY'], salt='flask-oidc-extra-data')
        self.cookie_serializer = JSONWebSignatureSerializer(
            app.config['SECRET_KEY'], salt='flask-oidc-cookie')

        try:
            self.credentials_store = app.config['OIDC_CREDENTIALS_STORE']
        except KeyError:
            pass
797605
def initialize_app(flask_app, args):
    """"""
    # Setup gourde with the args.
    gourde.setup(args)

    # Register a custom health check.
    gourde.is_healthy = is_healthy

    # Add an optional API
    initialize_api(flask_app)
980243
def init_app(self, app):
        
        app.url_rule_class = partial(NavigationRule, copilot=self)
        app.context_processor(self.inject_context)
55799
def init_app(self, app, env_file=None, verbose_mode=False):
        """"""
        if self.app is None:
            self.app = app
        self.verbose_mode = verbose_mode

        if env_file is None:
            env_file = os.path.join(os.getcwd(), ".env")
        if not os.path.exists(env_file):
            warnings.warn("can't read {0} - it doesn't exist".format(env_file))
        else:
            self.__import_vars(env_file)
1174334
def setup(app):
    

    app.add_config_value("cache_path", "_cache", "")

    try:
        os.makedirs(app.config.cache_path)
    except OSError as error:
        if error.errno != errno.EEXIST:
            raise

    path = os.path.join(app.config.cache_path, "spec.html")
    spec = fetch_or_load(path)
    app.add_role("validator", docutils_sucks(spec))
1045377
def init_app(self, app, decorators=None):
        
        self.decorators = decorators or self.decorators
        self.app = app

        self.load_config(app)
        # self.load_apispec(app)
        if self.template_file is not None:
            self.template = self.load_swagger_file(self.template_file)
        self.register_views(app)
        self.add_headers(app)

        if self.parse:
            if RequestParser is None:
                raise RuntimeError('Please install flask_restful')
            self.parsers = {}
            self.schemas = {}
            self.format_checker = jsonschema.FormatChecker()
            self.parse_request(app)

        self._configured = True
        app.swag = self
911687
def init_app(self, app):
        
        self.init_config(app)

        self.wrap_errorhandler(app)
        app.extensions['invenio-pages'] = _InvenioPagesState(app)

        return app.extensions['invenio-pages']
785173
def create_app(settings):
    """"""
    app = Flask(__name__)

    # Import settings from file
    for name in dir(settings):
        value = getattr(settings, name)
        if not (name.startswith('_') or isinstance(value, ModuleType)
                or isinstance(value, FunctionType)):
            app.config[name] = value

    # Bootstrapping
    if 'INSTALLED_APPS' in app.config:
        app.installed_apps = app.config.get('INSTALLED_APPS', [])

    # Extensions
    Funnel(app)
    Mobility(app)

    # Register blueprints
    for app_path in app.installed_apps:
        app.register_blueprint(
            getattr(__import__('{0}.views'.format(app_path),
                               fromlist=['blueprint']),
                    'blueprint'))

    # Register error handlers
    register_error_handlers(app)

    @app.context_processor
    def context_processor():
        return dict(config=app.config)

    @app.teardown_request
    def teardown_request(exception=None):
        # Remove the database session if it exists
        if hasattr(app, 'db_session'):
            app.db_session.close()

    return app
218948
def setup(self, app):
        
        super().setup(app)

        self.handlers = OrderedDict()

        # Connect admin templates
        app.ps.jinja2.cfg.template_folders.append(op.join(PLUGIN_ROOT, 'templates'))

        @app.ps.jinja2.filter
        def admtest(value, a, b=None):
            return a if value else b

        @app.ps.jinja2.filter
        def admeq(a, b, result=True):
            return result if a == b else not result

        @app.ps.jinja2.register
        def admurl(request, prefix):
            qs = {k: v for k, v in request.query.items() if not k.startswith(prefix)}
            if not qs:
                qs = {'ap': 0}
            return "%s?%s" % (request.path, urlparse.urlencode(qs))

        if self.cfg.name is None:
            self.cfg.name = "%s admin" % app.name.title()

        # Register a base view
        if not callable(self.cfg.home):

            def admin_home(request):
                yield from self.authorize(request)
                return app.ps.jinja2.render(self.cfg.template_home, active=None)

            self.cfg.home = admin_home

        app.register(self.cfg.prefix)(self.cfg.home)

        if not self.cfg.i18n:
            app.ps.jinja2.env.globals.update({
                '_': lambda s: s,
                'gettext': lambda s: s,
                'ngettext': lambda s, p, n: (n != 1 and (p,) or (s,))[0],
            })

            return

        if 'babel' not in app.ps or not isinstance(app.ps.babel, BPlugin):
            raise PluginException(
                'Plugin `%s` requires for plugin `%s` to be installed to the application.' % (
                    self.name, BPlugin))

        # Connect admin locales
        app.ps.babel.cfg.locales_dirs.append(op.join(PLUGIN_ROOT, 'locales'))
        if not app.ps.babel.locale_selector_func:
            app.ps.babel.locale_selector_func = app.ps.babel.select_locale_by_request
124781
def init_app(self, app):
        

        if self.__inited:
            return

        config = app.config.get(
            'FLASK_LOGGING_EXTRAS', {})

        blueprint_config = config.get('BLUEPRINT', {})
        self.bp_var = blueprint_config.get('FORMAT_NAME', 'blueprint')
        self.bp_app = blueprint_config.get('APP_BLUEPRINT', '<app>')
        self.bp_noreq = blueprint_config.get('NO_REQUEST_BLUEPRINT', '<not a request>')

        for var_name, resolver_fqn in config.get('RESOLVERS', {}).items():
            if resolver_fqn is None:
                resolver = None
            else:
                try:
                    resolver = _import_by_string(resolver_fqn)
                except ImportError:
                    resolver = resolver_fqn

            self.resolvers[var_name] = resolver

            self.__inited = True
25120
def init_app(self, app):
        
        if not hasattr(app, 'extensions'):  # pragma: no cover
            app.extensions = {}
        app.extensions['imagine'] = self

        self._set_defaults(app)

        self._redirect_code = app.config['IMAGINE_CACHE_REDIRECT_CODE']

        if isinstance(app.config['IMAGINE_ADAPTERS'], dict):
            self._adapters.update(app.config['IMAGINE_ADAPTERS'])
        if isinstance(app.config['IMAGINE_FILTERS'], dict):
            self._filters.update(app.config['IMAGINE_FILTERS'])

        self._handle_adapter(app)
        self._handle_filter_sets(app)

        self._add_url_rule(app)
1333588
def setup(self, app):
        """"""
        super().setup(app)

        self.enabled = len(self.cfg.backends)

        self.default = self.cfg.default
        if not self.default and self.enabled:
            self.default = self.cfg.backends[0][0]

        self.backends_hash = {name: parse.urlparse(loc) for (name, loc) in self.cfg.backends}
        if self.default and self.default not in self.backends_hash:
            raise PluginException('Backend not found: %s' % self.default)
976621
def init_app(self, app):
        
        config_log_level = app.config.get('FLASK_LOG_LEVEL', None)

        # Set up format for default logging
        hostname = platform.node().split('.')[0]
        formatter = (
            '[%(asctime)s] %(levelname)s %(process)d [%(name)s] '
            '%(filename)s:%(lineno)d - '
            '[{hostname}] - %(message)s'
        ).format(hostname=hostname)

        config_log_int = None
        set_level = None

        if config_log_level:
            config_log_int = getattr(logging, config_log_level.upper(), None)
            if not isinstance(config_log_int, int):
                raise ValueError(
                    'Invalid log level: {0}'.format(config_log_level)
                )
            set_level = config_log_int

        # Set to NotSet if we still aren't set yet
        if not set_level:
            set_level = config_log_int = logging.NOTSET
        self.log_level = set_level

        # Setup basic StreamHandler logging with format and level (do
        # setup in case we are main, or change root logger if we aren't.
        logging.basicConfig(format=formatter)
        root_logger = logging.getLogger()
        root_logger.setLevel(set_level)

        # Get everything ready to setup the syslog handlers
        address = None
        if os.path.exists('/dev/log'):
            address = '/dev/log'
        elif os.path.exists('/var/run/syslog'):
            address = '/var/run/syslog'
        else:
            address = ('127.0.0.1', 514)
        # Add syslog handler before adding formatters
        root_logger.addHandler(
            SysLogHandler(address=address, facility=SysLogHandler.LOG_LOCAL0)
        )
        self.set_formatter(formatter)

        return config_log_int
841769
def init_app(self, app):
        
        host = app.config.get('STATS_HOSTNAME', 'localhost')
        port = app.config.get('STATS_PORT', 8125)
        base_key = app.config.get('STATS_BASE_KEY', app.name)

        client = _StatsClient(
            host=host,
            port=port,
            prefix=base_key,
        )

        app.before_request(client.flask_time_start)
        app.after_request(client.flask_time_end)

        if not hasattr(app, 'extensions'):
            app.extensions = {}
        app.extensions.setdefault('stats', {})
        app.extensions['stats'][self] = client

        return client
897354
def init_app(self, app):
        

        for k, v in DEFAULT_SETTINGS.items():
            app.config.setdefault(k, v)

        if app.debug and not get_setting('FLASKS3_DEBUG', app):
            app.config['FLASKS3_ACTIVE'] = False

        if get_setting('FLASKS3_ACTIVE', app):
            app.jinja_env.globals['url_for'] = url_for
        if get_setting('FLASKS3_USE_CACHE_CONTROL', app) and app.config.get('FLASKS3_CACHE_CONTROL'):
            cache_control_header = get_setting('FLASKS3_CACHE_CONTROL', app)
            app.config['FLASKS3_HEADERS']['Cache-Control'] = cache_control_header
811564
def init_app(self, app):
        
        self._key = app.config.get(CONF_KEY) or getenv(CONF_KEY)

        if not self._key:
            return

        self._endpoint_uri = app.config.get(CONF_ENDPOINT_URI)
        sender = AsynchronousSender(self._endpoint_uri)

        queue = AsynchronousQueue(sender)
        self._channel = TelemetryChannel(None, queue)

        self._init_request_logging(app)
        self._init_trace_logging(app)
        self._init_exception_logging(app)
381576
def init_app(self, app):
        """"""
        app.add_url_rule(self.request_token_url, view_func=self.request_token,
                         methods=[u'POST'])
        app.add_url_rule(self.access_token_url, view_func=self.access_token,
                         methods=[u'POST'])
        app.add_url_rule(self.register_url, view_func=self.register,
                         methods=[u'GET', u'POST'])
        app.add_url_rule(self.authorize_url, view_func=self.authorize,
                         methods=[u'GET', u'POST'])