Initialize Flask application.
321473
def init_app(self, app):
        """"""
        if self.module:
            app.config.from_object(self.module)
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)
32141
def init_app(self, app, conf_key=None):
        
        conf_key = conf_key or self.conf_key or 'PYMEMCACHE'
        self.conf_key = conf_key
        conf = app.config[conf_key]
        if not isinstance(conf, dict):
            raise TypeError("Flask-PyMemcache conf should be dict")

        close_on_teardown = conf.pop('close_on_teardown', False)

        if isinstance(conf['server'], list):
            conf['servers'] = conf.pop('server')
            client = pymemcache.client.hash.HashClient(**conf)
        elif isinstance(conf['server'], tuple):
            client = pymemcache.client.Client(**conf)
        else:
            raise TypeError("Flask-PyMemcache conf['server'] should be tuple or list of tuples")

        app.extensions.setdefault('pymemcache', {})
        app.extensions['pymemcache'][self] = client

        if close_on_teardown:
            @app.teardown_appcontext
            def close_connection(exc=None):
                client.close()
817979
def init_app(self, app, session):
        
        app.config.setdefault("APP_NAME", "F.A.B.")
        app.config.setdefault("APP_THEME", "")
        app.config.setdefault("APP_ICON", "")
        app.config.setdefault("LANGUAGES", {"en": {"flag": "gb", "name": "English"}})
        app.config.setdefault("ADDON_MANAGERS", [])
        app.config.setdefault("FAB_API_MAX_PAGE_SIZE", 20)
        self.app = app
        if self.update_perms:  # default is True, if False takes precedence from config
            self.update_perms = app.config.get('FAB_UPDATE_PERMS', True)
        _security_manager_class_name = app.config.get('FAB_SECURITY_MANAGER_CLASS', None)
        if _security_manager_class_name is not None:
            self.security_manager_class = dynamic_class_import(
                _security_manager_class_name
            )
        if self.security_manager_class is None:
            from flask_appbuilder.security.sqla.manager import SecurityManager
            self.security_manager_class = SecurityManager

        self._addon_managers = app.config["ADDON_MANAGERS"]
        self.session = session
        self.sm = self.security_manager_class(self)
        self.bm = BabelManager(self)
        self.openapi_manager = OpenApiManager(self)
        self._add_global_static()
        self._add_global_filters()
        app.before_request(self.sm.before_request)
        self._add_admin_views()
        self._add_addon_views()
        if self.app:
            self._add_menu_permissions()
        else:
            self.post_init()
        self._init_extension(app)
475608
def create_app():
    """"""

    app = Flask(__name__)

    @app.before_request
    def before_request():
        if request.args.get('etree'):
            etree.to_etree()
        elif request.args.get('lxml'):
            etree.to_lxml()

    def _random(data, order):
        max = 10**order
        min = 10**random.randrange(0, order)

        series = []
        for i in range(random.randrange(1, 10)):
            values = [(
                random_value((-max, min)[random.randrange(0, 2)], max),
                random_value((-max, min)[random.randrange(0, 2)], max)
            ) for i in range(data)]
            series.append((random_label(), values, {}))
        return series

    def _random_series(type, data, order):
        max = 10**order
        min = 10**random.randrange(0, order)
        with_secondary = bool(random.randint(0, 1))
        series = []
        for i in range(random.randrange(1, 10)):
            if type == 'Pie':
                values = random_value(min, max)
            elif type == 'XY':
                values = [(
                    random_value((-max, min)[random.randrange(0, 2)], max),
                    random_value((-max, min)[random.randrange(0, 2)], max)
                ) for i in range(data)]
            else:
                values = [
                    random_value((-max, min)[random.randrange(1, 2)], max)
                    for i in range(data)
                ]
            config = {
                'secondary': with_secondary and bool(random.randint(0, 1))
            }
            series.append((random_label(), values, config))
        return series

    from .tests import get_test_routes
    links = get_test_routes(app)

    @app.route("/")
    def index():
        return render_template(
            'index.jinja2',
            styles=styles,
            parametric_styles=parametric_styles,
            parametric_colors=(
                '#ff5995', '#b6e354', '#feed6c', '#8cedff', '#9e6ffe'
            ),
            links=links,
            charts_name=pygal.CHARTS_NAMES
        )

    @app.route("/svg/<type>/<series>/<config>")
    def svg(type, series, config):
        graph = get(type)(pickle.loads(b64decode(str(config))))
        for title, values, serie_config in pickle.loads(b64decode(
                str(series))):
            graph.add(title, values, **serie_config)
        return graph.render_response()

    @app.route("/table/<type>/<series>/<config>")
    def table(type, series, config):
        graph = get(type)(pickle.loads(b64decode(str(config))))
        for title, values, serie_config in pickle.loads(b64decode(
                str(series))):
            graph.add(title, values, **serie_config)
        return graph.render_table()

    @app.route("/sparkline/<style>")
    @app.route("/sparkline/parameric/<style>/<color>")
    def sparkline(style, color=None):
        if color is None:
            style = styles[style]
        else:
            style = parametric_styles[style](color)

        line = pygal.Line(style=style, pretty_print=True)
        line.add('_', [random.randrange(0, 10) for _ in range(25)])
        return Response(
            line.render_sparkline(height=40), mimetype='image/svg+xml'
        )

    @app.route("/with/table/<type>")
    def with_table(type):
        chart = pygal.StackedBar(
            disable_xml_declaration=True, x_label_rotation=35
        )
        chart.title = (
            'What Linux distro do you primarily use'
            ' on your server computers? (Desktop'
            ' users vs Server Users)'
        )

        if type == 'series':
            chart.add('Debian', [1775, 82])
            chart.add('Ubuntu', [1515, 80])
            chart.add('CentOS', [807, 60])
            chart.add('Arch Linux', [549, 12])
            chart.add('Red Hat Enterprise Linux', [247, 10])
            chart.add('Gentoo', [129, 7])
            chart.add('Fedora', [91, 6])
            chart.add('Amazon Linux', [60, 0])
            chart.add('OpenSUSE', [58, 0])
            chart.add('Slackware', [50, 3])
            chart.add('Xubuntu', [38, 1])
            chart.add('Rasbian', [33, 4])
            chart.add('SUSE Linux Enterprise Server', [33, 1])
            chart.add('Linux Mint', [30, 4])
            chart.add('Scientific Linux', [32, 0])
            chart.add('Other', [187, 5])

        elif type == 'labels':
            chart.x_labels = [
                'Debian', 'Ubuntu', 'CentOS', 'Arch Linux',
                'Red Hat Enterprise Linux', 'Gentoo', 'Fedora', 'Amazon Linux',
                'OpenSUSE', 'Slackware', 'Xubuntu', 'Rasbian',
                'SUSE Linux Enterprise Server', 'Linux Mint',
                'Scientific Linux', 'Other'
            ]
            chart.add(
                'Desktop Users', [
                    1775, 1515, 807, 549, 247, 129, 91, 60, 58, 50, 38, 33, 33,
                    30, 32, 187
                ]
            )
            chart.add(
                'Server Users',
                [82, 80, 60, 12, 10, 7, 6, 0, 0, 3, 1, 4, 1, 4, 0, 5]
            )

        return render_template('table.jinja2', chart=chart)

    @app.route("/all")
    @app.route("/all/<style>")
    @app.route("/all/<style>/<color>")
    @app.route("/all/<style>/<color>/<base_style>")
    @app.route("/all/interpolate=<interpolate>")
    def all(style='default', color=None, interpolate=None, base_style=None):
        width, height = 600, 400
        data = random.randrange(1, 10)
        order = random.randrange(1, 10)
        if color is None:
            style = styles[style]
        else:
            style = parametric_styles[style](
                color, base_style=styles[base_style or 'default']
            )

        xy_series = _random(data, order)
        other_series = []
        for title, values, config in xy_series:
            other_series.append((title, cut(values, 1), config))
        xy_series = b64encode(pickle.dumps(xy_series))
        other_series = b64encode(pickle.dumps(other_series))
        config = Config()
        config.width = width
        config.height = height
        config.fill = bool(random.randrange(0, 2))
        config.interpolate = interpolate
        config.style = style
        svgs = []
        for chart in pygal.CHARTS:
            type = '.'.join((chart.__module__, chart.__name__))
            if chart._dual:
                config.x_labels = None
            else:
                config.x_labels = [random_label() for i in range(data)]
            svgs.append({
                'type': type,
                'series': xy_series if chart._dual else other_series,
                'config': b64encode(pickle.dumps(config))
            })

        return render_template(
            'svgs.jinja2', svgs=svgs, width=width, height=height
        )

    @app.route("/rotation")
    def rotation():
        width, height = 375, 245
        config = Config()
        config.width = width
        config.height = height
        config.fill = True
        config.style = styles['neon']
        data = random.randrange(1, 10)
        order = random.randrange(1, 10)
        series = b64encode(pickle.dumps(_random_series(type, data, order)))
        labels = [random_label() for i in range(data)]
        svgs = []
        config.show_legend = bool(random.randrange(0, 2))
        for angle in range(0, 370, 10):
            config.title = "%d rotation" % angle
            config.x_labels = labels
            config.x_label_rotation = angle
            config.y_label_rotation = angle
            svgs.append({
                'type': 'pygal.Bar',
                'series': series,
                'config': b64encode(pickle.dumps(config))
            })

        return render_template(
            'svgs.jinja2', svgs=svgs, width=width, height=height
        )

    @app.route("/interpolation")
    def interpolation():
        width, height = 600, 400
        config = Config()
        config.width = width
        config.height = height
        config.fill = True
        config.style = styles['neon']
        data = random.randrange(1, 10)
        order = random.randrange(1, 10)
        series = b64encode(pickle.dumps(_random_series(type, data, order)))
        svgs = []
        for interpolation in 'quadratic', 'cubic', 'lagrange', 'trigonometric':
            config.title = "%s interpolation" % interpolation
            config.interpolate = interpolation
            svgs.append({
                'type': 'pygal.StackedLine',
                'series': series,
                'config': b64encode(pickle.dumps(config))
            })

        for params in [{'type': 'catmull_rom'}, {'type': 'finite_difference'},
                       {'type': 'cardinal',
                        'c': .25}, {'type': 'cardinal',
                                    'c': .5}, {'type': 'cardinal', 'c': .75},
                       {'type': 'cardinal',
                        'c': 1.5}, {'type': 'cardinal',
                                    'c': 2}, {'type': 'cardinal', 'c': 5},
                       {'type': 'kochanek_bartels', 'b': 1, 'c': 1,
                        't': 1}, {'type': 'kochanek_bartels', 'b': -1, 'c': 1,
                                  't': 1}, {'type': 'kochanek_bartels', 'b': 1,
                                            'c': -1, 't': 1},
                       {'type': 'kochanek_bartels', 'b': 1, 'c': 1, 't': -1}, {
                           'type': 'kochanek_bartels', 'b': -1, 'c': 1, 't': -1
                       }, {'type': 'kochanek_bartels', 'b': -1, 'c': -1,
                           't': 1}, {'type': 'kochanek_bartels', 'b': -1,
                                     'c': -1, 't': -1}]:
            config.title = "Hermite interpolation with params %r" % params
            config.interpolate = 'hermite'
            config.interpolation_parameters = params
            svgs.append({
                'type': 'pygal.StackedLine',
                'series': series,
                'config': b64encode(pickle.dumps(config))
            })

        return render_template(
            'svgs.jinja2', svgs=svgs, width=width, height=height
        )

    @app.route("/raw_svgs/")
    def raw_svgs():
        svgs = []
        for color in styles['neon'].colors:
            chart = pygal.Pie(
                style=parametric_styles['rotate'](color),
                width=400,
                height=300
            )
            chart.title = color
            chart.disable_xml_declaration = True
            chart.explicit_size = True
            chart.js = ['http://l:2343/2.0.x/pygal-tooltips.js']
            for i in range(6):
                chart.add(str(i), 2**i)
            svgs.append(chart.render())
        return render_template('raw_svgs.jinja2', svgs=svgs)

    return app
963331
def init_app(self, app):
        
        app.config.setdefault('EDITS_URL', '/edits')
        app.config.setdefault('EDITS_PREVIEW', True)
        app.config.setdefault('EDITS_SUMMERNOTE', False)

        if 'EDITS_PATH' not in app.config:
            raise Exception('EDITS_PATH not set in app configuration.')

        if os.path.isfile(app.config['EDITS_PATH']):
            with open(app.config['EDITS_PATH']) as f:
                _db = json.loads(f.read(), object_pairs_hook=OrderedDict)
        else:
            _db = OrderedDict()

        app.jinja_env.add_extension('flask.ext.edits.EditableExtension')
        app.jinja_env.edits = _db
        app.jinja_env.edits_preview = app.config['EDITS_PREVIEW']
        app.jinja_env.edits_cache = copy_cache(app.jinja_env.cache)

        if app.config['EDITS_PREVIEW']:
            app.jinja_env.cache = None

        app.register_blueprint(edits, url_prefix=app.config['EDITS_URL'])
112331
def init(scope, app, settings):
    """"""
    cfg = settings.get('rw.static', {})
    static = Static()
    scope['static'] = static
    scope['template_env'].globals['static'] = static
    for base_uri, sources in cfg.items():
        full_paths = []
        for source in sources:
            if isinstance(source, dict):
                full_path = source['path']
                full_paths.append(full_path.format(**os.environ))
                continue
            elif ',' in source:
                module_name, path = [part.strip()
                                     for part in source.split(',')]
            else:
                module_name = source
                path = 'static'
            full_path = pkg_resources.resource_filename(module_name, path)
            full_paths.append(full_path)

        app.root.mount('/' + base_uri + '/<h>/<path:path>',
                       StaticHandler, {'path': full_paths},
                       name='static_' + base_uri.replace('.', '_'))

        static.handlers.append((base_uri, StaticHandler, full_paths))
    static.setup()
43554
def init_app(self, app):
        
        app.config.setdefault('OPENERP_SERVER', 'http://localhost:8069')
        app.config.setdefault('OPENERP_DATABASE', 'openerp')
        app.config.setdefault('OPENERP_DEFAULT_USER', 'admin')
        app.config.setdefault('OPENERP_DEFAULT_PASSWORD', 'admin')

        app.jinja_env.globals.update(
            get_data_from_record=get_data_from_record
        )

        cnx = Client(
            server=app.config['OPENERP_SERVER'],
            db=app.config['OPENERP_DATABASE'],
            user=app.config['OPENERP_DEFAULT_USER'],
            password=app.config['OPENERP_DEFAULT_PASSWORD']
        )

        self.default_user = cnx.user

        app.before_request(self.before_request)
854487
def init_app(self, app):
        """"""
        app.config.from_pyfile('{0}.cfg'.format(app.name), silent=True)
553719
def init_app(self, app):
        
        # Save this so we can use it later in the extension
        if not hasattr(app, 'extensions'):  # pragma: no cover
            app.extensions = {}
        app.extensions['flask-graphql-auth'] = self

        self._set_default__configuration_options(app)
463811
def init_app(self, app):
        """"""

        self.app = app
        self.app.apscheduler = self

        self._load_config()
        self._load_jobs()

        if self.api_enabled:
            self._load_api()
1120119
def init_app(self, app):
        
        self.init_config(app)

        # Enable CORS support if desired
        if app.config['REST_ENABLE_CORS']:
            from flask_cors import CORS
            CORS(app)
            # CORS can be configured using CORS_* configuration variables.

        app.errorhandler(400)(create_api_errorhandler(
            status=400, message='Bad Request'))
        app.errorhandler(401)(create_api_errorhandler(
            status=401, message='Unauthorized'))
        app.errorhandler(403)(create_api_errorhandler(
            status=403, message='Forbidden'))
        app.errorhandler(404)(create_api_errorhandler(
            status=404, message='Not Found'))
        app.errorhandler(405)(create_api_errorhandler(
            status=405, message='Method Not Allowed'))
        app.errorhandler(406)(create_api_errorhandler(
            status=406, message='Not Acceptable'))
        app.errorhandler(409)(create_api_errorhandler(
            status=409, message='Conflict'))
        app.errorhandler(410)(create_api_errorhandler(
            status=410, message='Gone'))
        app.errorhandler(412)(create_api_errorhandler(
            status=412, message='Precondition Failed'))
        app.errorhandler(415)(create_api_errorhandler(
            status=415, message='Unsupported media type'))
        app.errorhandler(422)(create_api_errorhandler(
            status=422, message='Unprocessable Entity'))
        app.errorhandler(429)(create_api_errorhandler(
            status=429, message='Rate limit exceeded'))
        app.errorhandler(500)(create_api_errorhandler(
            status=500, message='Internal Server Error'))
        app.errorhandler(501)(create_api_errorhandler(
            status=501, message='Not Implemented'))
        app.errorhandler(502)(create_api_errorhandler(
            status=502, message='Bad Gateway'))
        app.errorhandler(503)(create_api_errorhandler(
            status=503, message='Service Unavailable'))
        app.errorhandler(504)(create_api_errorhandler(
            status=504, message='Gateway Timeout'))

        app.extensions['invenio-rest'] = self
418217
def init_app(self, app):
        """"""
        self.init_config(app)
        app.cli.add_command(classifier_cmd)
        app.extensions['invenio-classifier'] = self
713218
def init_app(self, app):
        
        if (
            'SQLALCHEMY_DATABASE_URI' not in app.config and
            'SQLALCHEMY_BINDS' not in app.config
        ):
            warnings.warn(
                'Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. '
                'Defaulting SQLALCHEMY_DATABASE_URI to "sqlite:///:memory:".'
            )

        app.config.setdefault('SQLALCHEMY_DATABASE_URI', 'sqlite:///:memory:')
        app.config.setdefault('SQLALCHEMY_BINDS', None)
        app.config.setdefault('SQLALCHEMY_NATIVE_UNICODE', None)
        app.config.setdefault('SQLALCHEMY_ECHO', False)
        app.config.setdefault('SQLALCHEMY_RECORD_QUERIES', None)
        app.config.setdefault('SQLALCHEMY_POOL_SIZE', None)
        app.config.setdefault('SQLALCHEMY_POOL_TIMEOUT', None)
        app.config.setdefault('SQLALCHEMY_POOL_RECYCLE', None)
        app.config.setdefault('SQLALCHEMY_MAX_OVERFLOW', None)
        app.config.setdefault('SQLALCHEMY_COMMIT_ON_TEARDOWN', False)
        track_modifications = app.config.setdefault(
            'SQLALCHEMY_TRACK_MODIFICATIONS', None
        )
        app.config.setdefault('SQLALCHEMY_ENGINE_OPTIONS', {})

        if track_modifications is None:
            warnings.warn(FSADeprecationWarning(
                'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
                'will be disabled by default in the future.  Set it to True '
                'or False to suppress this warning.'
            ))

        # Deprecation warnings for config keys that should be replaced by SQLALCHEMY_ENGINE_OPTIONS.
        utils.engine_config_warning(app.config, '3.0', 'SQLALCHEMY_POOL_SIZE', 'pool_size')
        utils.engine_config_warning(app.config, '3.0', 'SQLALCHEMY_POOL_TIMEOUT', 'pool_timeout')
        utils.engine_config_warning(app.config, '3.0', 'SQLALCHEMY_POOL_RECYCLE', 'pool_recycle')
        utils.engine_config_warning(app.config, '3.0', 'SQLALCHEMY_MAX_OVERFLOW', 'max_overflow')

        app.extensions['sqlalchemy'] = _SQLAlchemyState(self)

        @app.teardown_appcontext
        def shutdown_session(response_or_exc):
            if app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']:
                if response_or_exc is None:
                    self.session.commit()

            self.session.remove()
            return response_or_exc
372898
def init_app(self, app):
        

        self.__app = app
        self.__app.before_first_request(self.__setup)

        self.tracer.enabled = self.__app.config.get('TRACE_ENABLED', self.tracer.enabled)
1213952
def init_db(self, app, entry_point_group='invenio_db.models', **kwargs):
        """"""
        # Setup SQLAlchemy
        app.config.setdefault(
            'SQLALCHEMY_DATABASE_URI',
            'sqlite:///' + os.path.join(app.instance_path, app.name + '.db')
        )
        app.config.setdefault('SQLALCHEMY_ECHO', False)

        # 
        database = kwargs.get('db', db)
        database.init_app(app)

        # Initialize versioning support.
        self.init_versioning(app, database, kwargs.get('versioning_manager'))

        # Initialize model bases
        if entry_point_group:
            for base_entry in pkg_resources.iter_entry_points(
                    entry_point_group):
                base_entry.load()

        # All models should be loaded by now.
        sa.orm.configure_mappers()
        # Ensure that versioning classes have been built.
        if app.config['DB_VERSIONING']:
            manager = self.versioning_manager
            if manager.pending_classes:
                if not versioning_models_registered(manager, database.Model):
                    manager.builder.configure_versioned_classes()
            elif 'transaction' not in database.metadata.tables:
                manager.declarative_base = database.Model
                manager.create_transaction_model()
                manager.plugins.after_build_tx_class(manager)
474093
def init_app(self, app):
        """"""
        super(InvenioIIIFAPI, self).init_app(app)
        api = Api(app=app)
        self.iiif_ext.init_restful(api, prefix=app.config['IIIF_API_PREFIX'])