Configure the current Flask app with an instance of ``CubeManager`` that
    will be used to load and query data.
491710
def configure_api(app, manager):
    
    if not hasattr(app, 'extensions'):
        app.extensions = {}  # pragma: nocover
    app.extensions['babbage'] = manager
    return blueprint
249470
def init_app(self, app, entry_point_group='invenio_celery.tasks',
                 **kwargs):
        """"""
        self.init_config(app)
        self.celery = FlaskCeleryExt(app).celery
        self.entry_point_group = entry_point_group
        app.extensions['invenio-celery'] = self
536575
def init_config(self, app):
        
        app.config.setdefault('REQUIREJS_BASEURL', app.static_folder)
        app.config.setdefault('COLLECT_STATIC_ROOT', app.static_folder)
        app.config.setdefault('COLLECT_STORAGE', 'flask_collect.storage.link')
        app.config.setdefault(
            'COLLECT_FILTER', partial(collect_staticroot_removal, app))
        app.config.setdefault(
            'WEBPACKEXT_PROJECT', 'invenio_assets.webpack:project')
602578
def setup(self, app):
        
        super().setup(app)

        if isinstance(self.cfg.template_folders, str):
            self.cfg.template_folders = [self.cfg.template_folders]

        self.cfg.template_folders = list(self.cfg.template_folders)
        if not self.cfg.loader:
            self.cfg.loader = FileSystemLoader(
                self.cfg.template_folders, encoding=self.cfg.encoding)

        self.env = jinja2.Environment(
            auto_reload=self.cfg.auto_reload,
            cache_size=self.cfg.cache_size,
            extensions=self.cfg.extensions,
            loader=self.cfg.loader,
        )
        self.env.globals['app'] = app

        @self.register
        @jinja2.contextfunction
        def debug(ctx, value=None):
            """ Debug current context to template. """
            return jinja2.filters.do_pprint(value is None and ctx or value)

        @self.filter
        def jsonify(obj):
            return dumps(obj, ensure_ascii=False, encode_html_chars=True)
508378
def create(self):
        
        self._app = Flask(__name__)

        path = '/2015-03-31/functions/<function_name>/invocations'
        self._app.add_url_rule(path,
                               endpoint=path,
                               view_func=self._invoke_request_handler,
                               methods=['POST'],
                               provide_automatic_options=False)

        # setup request validation before Flask calls the view_func
        self._app.before_request(LocalLambdaInvokeService.validate_request)

        self._construct_error_handling()
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
121118
def create_app():
    """"""
    app = Flask(__name__)
    app.config_from_envvar = app.config.from_envvar
    app.config_from_object = app.config.from_object
    configure_app(app)
    init_core(app)
    register_blueprints(app)
    return app
357114
def bind(cls, app, *paths, methods=None, name=None, router=None, view=None):
        """"""
        cls.app = app
        if cls.app is not None:
            for _, m in inspect.getmembers(cls, predicate=inspect.isfunction):
                if not hasattr(m, ROUTE_PARAMS_ATTR):
                    continue
                paths_, methods_, name_ = getattr(m, ROUTE_PARAMS_ATTR)
                name_ = name_ or ("%s.%s" % (cls.name, m.__name__))
                delattr(m, ROUTE_PARAMS_ATTR)
                cls.app.register(*paths_, methods=methods_, name=name_, handler=cls)(m)

        @coroutine
        @functools.wraps(cls)
        def handler(request):
            return cls().dispatch(request, view=view)

        if not paths:
            paths = ["/%s" % cls.__name__]

        return routes_register(
            app, handler, *paths, methods=methods, router=router, name=name or cls.name)
379511
def main(global_config, **settings):
    
    config = Configurator(settings=settings)
    config.set_session_factory(session_factory)
    config.include('pyramid_jinja2')
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('index', '/')
    config.add_route('attrs', '/attrs/')
    config.add_route('metadata', '/metadata/')
    config.scan()
    return config.make_wsgi_app()
839229
def get_new_configured_app(dispatcher, path=DEFAULT_WEB_PATH):
    
    app = web.Application()
    configure_app(dispatcher, app, path)
    return app
1038707
def create_app():
    
    
    # Setup Flask and load app.config
    app = Flask(__name__)
    app.config.from_object(__name__+'.ConfigClass')

    # Setup Flask-MongoEngine
    db = MongoEngine(app)

    # Define the User document.
    # NB: Make sure to add flask_user UserMixin !!!
    class User(db.Document, UserMixin):
        active = db.BooleanField(default=True)

        # User authentication information
        username = db.StringField(default='')
        password = db.StringField()

        # User information
        first_name = db.StringField(default='')
        last_name = db.StringField(default='')

        # Relationships
        roles = db.ListField(db.StringField(), default=[])

    # Setup Flask-User and specify the User data-model
    user_manager = UserManager(app, db, User)

    # The Home page is accessible to anyone
    @app.route('/')
    def home_page():
        # String-based templates
        return render_template_string("""
            {% extends "flask_user_layout.html" %}
            {% block content %}
                <h2>Home page</h2>
                <p><a href={{ url_for('user.register') }}>Register</a></p>
                <p><a href={{ url_for('user.login') }}>Sign in</a></p>
                <p><a href={{ url_for('home_page') }}>Home page</a> (accessible to anyone)</p>
                <p><a href={{ url_for('member_page') }}>Member page</a> (login required)</p>
                <p><a href={{ url_for('user.logout') }}>Sign out</a></p>
            {% endblock %}
            """)

    # The Members page is only accessible to authenticated users via the @login_required decorator
    @app.route('/members')
    @login_required    # User must be authenticated
    def member_page():
        # String-based templates
        return render_template_string("""
            {% extends "flask_user_layout.html" %}
            {% block content %}
                <h2>Members page</h2>
                <p><a href={{ url_for('user.register') }}>Register</a></p>
                <p><a href={{ url_for('user.login') }}>Sign in</a></p>
                <p><a href={{ url_for('home_page') }}>Home page</a> (accessible to anyone)</p>
                <p><a href={{ url_for('member_page') }}>Member page</a> (login required)</p>
                <p><a href={{ url_for('user.logout') }}>Sign out</a></p>
            {% endblock %}
            """)

    return app
189285
def initialize_api(flask_app):
    """"""
    if not flask_restplus:
        return

    api = flask_restplus.Api(version="1.0", title="My Example API")
    api.add_resource(HelloWorld, "/hello")

    blueprint = flask.Blueprint("api", __name__, url_prefix="/api")
    api.init_app(blueprint)
    flask_app.register_blueprint(blueprint)
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'])
1103340
def initialize(self, app: Flask, app_config):
        
        debug = app_config["debug"]
        port = app_config["http.port"]
        if debug:
            self.started_on_port = port
            app.run(host="0.0.0.0", debug=True, port=port)
        else:
            for port in range(port, port + 50):
                self.http_server = WSGIServer(('0.0.0.0', port), app)
                try:
                    self.http_server.start()
                except OSError:
                    # try next port
                    continue
                self.started_on_port = port
                break
1360650
def create_app(config_filename, instance_path=None):
    
    app_ = CustomFlask(
        __name__,
        instance_path=instance_path or os.environ.get(
            'VERIPRESS_INSTANCE_PATH') or os.getcwd(),
        instance_relative_config=True
    )
    app_.config.update(dict(STORAGE_TYPE='file',
                            THEME='default',
                            CACHE_TYPE='simple',
                            MODE='view-only',
                            ENTRIES_PER_PAGE=5,
                            FEED_COUNT=10,
                            SHOW_TOC=True,
                            TOC_DEPTH=3,
                            TOC_LOWEST_LEVEL=3,
                            ALLOW_SEARCH_PAGES=True,
                            PAGE_SOURCE_ACCESSIBLE=False))
    app_.config.from_pyfile(config_filename, silent=True)

    theme_folder = os.path.join(app_.instance_path,
                                'themes', app_.config['THEME'])
    # use templates in the selected theme's folder
    app_.template_folder = os.path.join(theme_folder, 'templates')
    # use static files in the selected theme's folder
    app_.theme_static_folder = os.path.join(theme_folder, 'static')
    # global static folder
    app_.static_folder = os.path.join(app_.instance_path, 'static')

    return app_
24087
def main(global_config, **settings):
    
    # Initialize the database
    engine = engine_from_config(settings, 'sqlalchemy.')
    configure_sql(engine)

    secure_cookies = settings.get('secure_cookies') != 'false'
    if 'pyramid_debugtoolbar' in settings['pyramid.includes']:
        create_schema(global_config['__file__'])
        populate_database()
        secure_cookies = False

    # Configure the webapp
    authen = AuthTktAuthenticationPolicy(secret=settings['auth_secret'],
                                         callback=group_finder,
                                         secure=secure_cookies,
                                         include_ip=False, hashalg='sha512',
                                         wild_domain=False, max_age=5000000)
    author = ACLAuthorizationPolicy()
    session_factory = UnencryptedCookieSessionFactoryConfig(
        settings['cookie_secret'])
    config = Configurator(settings=settings, authentication_policy=authen,
                          authorization_policy=author, root_factory=Root,
                          session_factory=session_factory)
    config.add_static_view('static', 'static', cache_max_age=3600)
    # Add attributes to request
    config.add_request_method(get_user, 'user', reify=True)
    config.add_request_method(get_queue_func, 'queue', reify=True)

    add_routes(config)
    config.scan()
    return config.make_wsgi_app()
1057644
def setup_cache(app: Flask, cache_config) -> Optional[Cache]:
    """"""
    if cache_config and cache_config.get('CACHE_TYPE') != 'null':
        return Cache(app, config=cache_config)

    return None