Create a WSGI app which serves the metrics from a registry.
320380
def make_wsgi_app(registry=REGISTRY):
    """"""

    def prometheus_app(environ, start_response):
        params = parse_qs(environ.get('QUERY_STRING', ''))
        r = registry
        encoder, content_type = choose_encoder(environ.get('HTTP_ACCEPT'))
        if 'name[]' in params:
            r = r.restricted_registry(params['name[]'])
        output = encoder(r)

        status = str('200 OK')
        headers = [(str('Content-type'), content_type)]
        start_response(status, headers)
        return [output]

    return prometheus_app
1209474
def setup_prometheus(self, registry=None):
        """"""
        kwargs = {}
        if registry:
            kwargs["registry"] = registry
        self.metrics = PrometheusMetrics(self.app, **kwargs)
        try:
            version = pkg_resources.require(self.app.name)[0].version
        except pkg_resources.DistributionNotFound:
            version = "unknown"
        self.metrics.info(
            "app_info", "Application info", version=version, appname=self.app.name
        )
        self.app.logger.info("Prometheus is enabled.")
1180747
def register_endpoint(self, path, app=None):
        

        if is_running_from_reloader() and not os.environ.get('DEBUG_METRICS'):
            return

        if app is None:
            app = self.app or current_app

        @app.route(path)
        @self.do_not_track()
        def prometheus_metrics():
            # import these here so they don't clash with our own multiprocess module
            from prometheus_client import multiprocess, CollectorRegistry

            if 'prometheus_multiproc_dir' in os.environ:
                registry = CollectorRegistry()
            else:
                registry = self.registry

            if 'name[]' in request.args:
                registry = registry.restricted_registry(request.args.getlist('name[]'))

            if 'prometheus_multiproc_dir' in os.environ:
                multiprocess.MultiProcessCollector(registry)

            headers = {'Content-Type': CONTENT_TYPE_LATEST}
            return generate_latest(registry), 200, headers
124625
def web(host, port):
    """"""
    from .webserver.web import get_app
    get_app().run(host=host, port=port)
245022
def marvcli_develop_server(port, public):
    
    from flask_cors import CORS
    app = create_app(push=False)
    app.site.load_for_web()
    CORS(app)

    class IPDBMiddleware(object):
        def __init__(self, app):
            self.app = app

        def __call__(self, environ, start_response):
            from ipdb import launch_ipdb_on_exception
            with launch_ipdb_on_exception():
                appiter = self.app(environ, start_response)
                for item in appiter:
                    yield item

    app.debug = True
    if IPDB:
        app.wsgi_app = IPDBMiddleware(app.wsgi_app)
        app.run(use_debugger=False,
                use_reloader=False,
                host=('0.0.0.0' if public else '127.0.0.1'),
                port=port,
                threaded=False)
    else:
        app.run(host=('0.0.0.0' if public else '127.0.0.1'),
                port=port,
                reloader_type='watchdog',
                threaded=False)
863783
def create_app(cls, port):
        
        app = FrontEndApp()
        app_server = GeventServer(app, port=port, hostname='0.0.0.0')
        return app_server
787203
def gather_data(registry):
    """"""

    # Get the host name of the machine
    host = socket.gethostname()

    # Create our collectors
    trig_metric = Gauge("trigonometry_example",
                        "Various trigonometry examples.",
                        {'host': host})

    # register the metric collectors
    registry.register(trig_metric)

    # Start gathering metrics every second
    counter = 0
    while True:
        time.sleep(1)

        sine = math.sin(math.radians(counter % 360))
        cosine = math.cos(math.radians(counter % 360))
        trig_metric.set({'type': "sine"}, sine)
        trig_metric.set({'type': "cosine"}, cosine)

        counter += 1
828416
def init_app(application):
    
    config = {k: v for k, v in application.config.items() if k in SCHEMA}

    kwargs = {'autorefresh': application.debug}

    kwargs.update((k[11:].lower(), v) for k, v in config.items())

    instance = whitenoise.WhiteNoise(application.wsgi_app, **kwargs)

    instance.add_files(application.static_folder, application.static_url_path)

    if not hasattr(application, 'extensions'):
        application.extensions = {}

    application.extensions['whitenoise'] = instance

    application.wsgi_app = instance
638085
def create_app(**config):
    
    app = Flask(
        __name__, static_folder=None
    )

    if 'MONGO_URI' in os.environ:
        app.config['MONGO_URI'] = os.environ['MONGO_URI']

    app.config['LOG_LEVEL'] = 'DEBUG'
    app.config['SECRET_KEY'] = '2205552d13b5431bb537732bbb051f1214414f5ab34d47'

    configure_logging(app)
    configure_sentry(app)
    configure_api(app)
    configure_mongodb(app)
    configure_login(app)

    return app
15017
def serve(application, host='127.0.0.1', port=8080):
	
	
	# Instantiate the server with a host/port configuration and our application.
	WSGIApplication(application, port=int(port), iface=host).run()
1169456
def wsgi(self, environ, start_response):
        """"""
        request = Request(environ)
        ctx = Context(request)
        try:
            try:
                response = self(request, ctx)
                ctx._run_callbacks('finalize', (request, response))
                response = response.conditional_to(request)
            except HTTPException as e:
                response = e.response
            except Exception:
                self.handle_error(request, ctx)
                response = InternalServerError().response

            response.add_callback(lambda: ctx._run_callbacks('close'))
            return response(environ, start_response)
        finally:
            ctx._run_callbacks('teardown', log_errors=True)
639658
def _init_request_logging(self, app):
        
        enabled = not app.config.get(CONF_DISABLE_REQUEST_LOGGING, False)

        if not enabled:
            return

        self._requests_middleware = WSGIApplication(
            self._key, app.wsgi_app, telemetry_channel=self._channel)

        app.wsgi_app = self._requests_middleware
1200138
def set_server(self, wsgi_app, fnc_serve=None):
        

        self.set_wsgi_app(wsgi_app)

        ssl_config = self.get_config("ssl")
        ssl_context = {}

        if self.get_config("server") == "gevent":

            if ssl_config.get("enabled"):
                ssl_context["certfile"] = ssl_config.get("cert")
                ssl_context["keyfile"] = ssl_config.get("key")

            from gevent.pywsgi import WSGIServer

            http_server = WSGIServer(
                (self.host, self.port),
                wsgi_app,
                **ssl_context
            )

            self.log.debug("Serving WSGI via gevent.pywsgi.WSGIServer")

            fnc_serve = http_server.serve_forever

        elif self.get_config("server") == "uwsgi":
            self.pluginmgr_config["start_manual"] = True

        elif self.get_config("server") == "gunicorn":
            self.pluginmgr_config["start_manual"] = True

        elif self.get_config("server") == "self":
            fnc_serve = self.run

        # figure out async handler

        if self.get_config("async") == "gevent":

            # handle async via gevent
            import gevent

            self.log.debug("Handling wsgi on gevent")

            self.worker = gevent.spawn(fnc_serve)

        elif self.get_config("async") == "thread":

            self.worker = fnc_serve

        else:

            self.worker = fnc_serve
1316326
def setup_app(app, cfg):
    
    # Set up app_host and app_port in case that we are running
    # under reverse proxy setup, otherwise they default to
    # config.host and config.port.
    if (cfg.app_host and cfg.app_port):
        logging.warning("Reverse proxy for service at http://%s:%d/ ..." % (cfg.host, cfg.port))
        app.wsgi_app = ReverseProxied(app.wsgi_app, cfg.host)
    elif (cfg.app_host or cfg.app_port):
        logging.critical("Must specify both app-host and app-port for reverse proxy configuration, aborting")
        sys.exit(1)
    else:
        cfg.app_host = cfg.host
        cfg.app_port = cfg.port
    logging.warning("Setup server on http://%s:%d/ ..." % (cfg.app_host, cfg.app_port))
    return(app)
1046320
def start_server(self, host='localhost', port=9000, app=None):
        """"""
        from wsgiref.simple_server import make_server
        if app is None:
            app = self.wsgi
        server = make_server(host, port, app)
        server_addr = "%s:%s" % (server.server_name, server.server_port)
        print "Server listening at http://%s/" % server_addr
        server.serve_forever()
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
3813
def create_gw_response(app, wsgi_env):
    
    response = {}
    buf = []
    result = []

    def start_response(status, headers, exc_info=None):
        result[:] = [status, headers]
        return buf.append

    appr = app(wsgi_env, start_response)
    close_func = getattr(appr, 'close', None)
    try:
        buf.extend(list(appr))
    finally:
        close_func and close_func()

    response['body'] = ''.join(buf)
    response['statusCode'] = result[0].split(' ', 1)[0]
    response['headers'] = {}

    for k, v in result[1]:
        response['headers'][k] = v
    if 'Content-Length' not in response['headers']:
        response['headers']['Content-Length'] = str(len(response['body']))
    if 'Content-Type' not in response['headers']:
        response['headers']['Content-Type'] = 'text/plain'
    return response