Do some setup and return the wsgi app.
165185
def build_application(conf):
    """"""
    if isinstance(conf.adapter_options, list):
        conf['adapter_options'] = {key: val for _dict in conf.adapter_options
                                   for key, val in _dict.items()}
    elif conf.adapter_options is None:
        conf['adapter_options'] = {}
    else:
        conf['adapter_options'] = copy.copy(conf.adapter_options)

    # get wsgi app the same way bottle does if it receives a string.
    conf['app'] = conf.app or bottle.default_app()
    if isinstance(conf.app, six.string_types):
        conf['app'] = bottle.load_app(conf.app)

    def _find_bottle_app(_app):
        """Lookup the underlying Bottle() instance."""
        while hasattr(_app, 'app'):
            if isinstance(_app, bottle.Bottle):
                break
            _app = _app.app
        assert isinstance(_app, bottle.Bottle), 'Could not find Bottle app.'
        return _app

    bottle_app = _find_bottle_app(conf.app)
    bottle_app.route(
        path='/_simpl', method='GET', callback=_version_callback)

    def _show_routes():
        """Conditionally print the app's routes."""
        if conf.app and not conf.quiet:
            if conf.reloader and os.getenv('BOTTLE_CHILD'):
                LOG.info("Running bottle server with reloader.")
            elif not conf.reloader:
                pass
            else:
                return
            routes = fmt_routes(bottle_app)
            if routes:
                    print('\n{}'.format(routes), end='\n\n')
    _show_routes()
    return conf.app
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
958766
def _get_webapp(self):
        
        settings = {
            "PORT"          : self._port,
            #"static_path"   : app_path(__conf__.STATIC_DIR_NAME),
            #"template_path" : app_path(__conf__.TEMPLATE_DIR_NAME),
            "debug"         : __conf__.DEBUG,
            "cookie_secret" : __conf__.COOKIE_SECRET
        }

        self.settings.update(settings)
        return WebApplication(self._handlers, **settings)
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
899973
def create_app(config='udata.settings.Defaults', override=None,
               init_logging=init_logging):
    ''''''
    app = UDataApp(APP_NAME)
    app.config.from_object(config)

    settings = os.environ.get('UDATA_SETTINGS', join(os.getcwd(), 'udata.cfg'))
    if exists(settings):
        app.settings_file = settings  # Keep track of loaded settings for diagnostic
        app.config.from_pyfile(settings)

    if override:
        app.config.from_object(override)

    # Loads defaults from plugins
    for pkg in entrypoints.get_roots(app):
        if pkg == 'udata':
            continue  # Defaults are already loaded
        module = '{}.settings'.format(pkg)
        if pkgutil.find_loader(module):
            settings = pkgutil.get_loader(module)
            for key, default in settings.__dict__.items():
                app.config.setdefault(key, default)

    app.json_encoder = UDataJsonEncoder

    app.debug = app.config['DEBUG'] and not app.config['TESTING']

    app.wsgi_app = ProxyFix(app.wsgi_app)

    init_logging(app)
    register_extensions(app)

    return app
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
1266511
def run(config):
    ""
    app = make_app(config=config)

    app.run(
            host=app.config.get("HOST", '127.0.0.1'),
            port=app.config.get("PORT", 5000),
            use_reloader=True,
            )
1191282
def init_app(self, app):
        
        app.config.setdefault('FLASK_AUTH_ALL', False)
        app.config.setdefault('FLASK_AUTH_REALM', 'Login Required')
        # Default set to bad file to trigger IOError
        app.config.setdefault('FLASK_HTPASSWD_PATH', '/^^^/^^^')

        # Load up user database
        try:
            self.load_users(app)
        except IOError:
            log.critical(
                'No htpasswd file loaded, please set `FLASK_HTPASSWD`'
                'or `FLASK_HTPASSWD_PATH` environment variable to a '
                'valid apache htpasswd file.'
            )

        # Allow requiring auth for entire app, with pre request method
        @app.before_request
        def require_auth():  # pylint: disable=unused-variable
            """Pre request processing for enabling full app authentication."""
            if not current_app.config['FLASK_AUTH_ALL']:
                return
            is_valid, user = self.authenticate()
            if not is_valid:
                return self.auth_failed()
            g.user = user
887015
def setup(self, app):
        """"""
        super().setup(app)

        if self.cfg.secret == 'InsecureSecret':
            app.logger.warning(
                'Use insecure secret key. Change SESSION_SECRET option in configuration.')

        self._user_loader = asyncio.coroutine(lambda id_: id_)  # noqa

        app.on_response_prepare.append(self.save)

        if self.cfg.auto_load:
            app.middlewares.append(self._middleware)
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
753113
def setup(self, environ):
        ''''''
        json_handler = Root().putSubHandler('calc', Calculator())
        middleware = wsgi.Router('/', post=json_handler,
                                 accept_content_types=JSON_CONTENT_TYPES)
        response = [wsgi.GZipMiddleware(200)]
        return wsgi.WsgiHandler(middleware=[wsgi.wait_for_body_middleware,
                                            middleware],
                                response_middleware=response)
1087392
def app(environ, start_response):
    
    from wsgi import container

    """Add Environ To Service Container
    Add the environ to the service container. The environ is generated by the
    the WSGI server above and used by a service provider to manipulate the
    incoming requests
    """

    container.bind('Environ', environ)

    """Execute All Service Providers That Require The WSGI Server
    Run all service provider boot methods if the wsgi attribute is true.
    """

    try:
        for provider in container.make('WSGIProviders'):
            container.resolve(provider.boot)
    except Exception as e:
        container.make('ExceptionHandler').load_exception(e)

    """We Are Ready For Launch
    If we have a solid response and not redirecting then we need to return
    a 200 status code along with the data. If we don't, then we'll have
    to return a 302 redirection to where ever the user would like go
    to next.
    """

    start_response(container.make('Request').get_status_code(),
                   container.make('Request').get_and_reset_headers())

    """Final Step
    This will take the data variable from the Service Container and return
    it to the WSGI server.
    """

    return iter([bytes(container.make('Response'), 'utf-8')])
124625
def web(host, port):
    """"""
    from .webserver.web import get_app
    get_app().run(host=host, port=port)
945543
def serve(config):
    ""
    from gevent.pywsgi import WSGIServer

    app = make_app(config=config)

    host = app.config.get("HOST", '127.0.0.1')
    port = app.config.get("PORT", 5000)
    http_server = WSGIServer((host, port), app)
    http_server.serve_forever()
1037826
def setup(self, app: web.Application):
        
        if self.app is app:
            raise ValueError('The router is already configured '
                             'for this application')
        self.app = app
        routes = sorted(
            ((r.name, (r, r.url_for().human_repr())) for r in self.routes()),
            key=utils.sort_key)
        exists = set()  # type: Set[str]
        for name, (route, path) in routes:
            if name and name not in exists:
                exists.add(name)
            else:
                name = None
            app.router.add_route(
                route.method, path,
                route.handler, name=name)
694414
def get_application(*args):
    '''
    
    '''
    opts_tuple = args

    def wsgi_app(environ, start_response):
        root, _, conf = opts_tuple or bootstrap_app()
        cherrypy.config.update({'environment': 'embedded'})

        cherrypy.tree.mount(root, '/', conf)
        return cherrypy.tree(environ, start_response)

    return wsgi_app
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)