Load all apis, either as local apis served by the flask app, or as
        remote apis to be called from whithin the app's endpoints, then start
        the app server
425111
def start(self, serve=[]):
        """"""

        # Check arguments
        if type(serve) is str:
            serve = [serve]
        elif type(serve) is list:
            pass
        else:
            raise Exception("'serve' should be an api name or a list of api names")

        if len(serve) == 0:
            raise Exception("You must specify at least one api to serve")

        for api_name in serve:
            if api_name not in self.apis:
                raise Exception("Can't find %s.yaml (swagger file) in the api directory %s" % (api_name, self.path_apis))

        app = self.app
        app.secret_key = os.urandom(24)

        # Initialize JWT config
        conf = get_config()
        if hasattr(conf, 'jwt_secret'):
            log.info("Set JWT parameters to issuer=%s audience=%s secret=%s***" % (
                conf.jwt_issuer,
                conf.jwt_audience,
                conf.jwt_secret[0:8],
            ))

        # Always serve the ping api
        serve.append('ping')

        # Let's compress returned data when possible
        compress = Compress()
        compress.init_app(app)

        # All apis that are not served locally are not persistent
        not_persistent = []
        for api_name in self.apis.keys():
            if api_name in serve:
                pass
            else:
                not_persistent.append(api_name)

        # Now load those apis into the ApiPool
        for api_name, api_path in self.apis.items():

            host = None
            port = None

            if api_name in serve:
                # We are serving this api locally: override the host:port specified in the swagger spec
                host = self.host
                port = self.port

            do_persist = True if api_name not in not_persistent else False
            local = True if api_name in serve else False

            log.info("Loading api %s from %s (persist: %s)" % (api_name, api_path, do_persist))
            ApiPool.add(
                api_name,
                yaml_path=api_path,
                timeout=self.timeout,
                error_callback=self.error_callback,
                formats=self.formats,
                do_persist=do_persist,
                host=host,
                port=port,
                local=local,
            )

        ApiPool.merge()

        # Now spawn flask routes for all endpoints
        for api_name in self.apis.keys():
            if api_name in serve:
                log.info("Spawning api %s" % api_name)
                api = getattr(ApiPool, api_name)
                # Spawn api and wrap every endpoint in a crash handler that
                # catches replies and reports errors
                api.spawn_api(app, decorator=generate_crash_handler_decorator(self.error_decorator))

        log.debug("Argv is [%s]" % '  '.join(sys.argv))
        if 'celery' in sys.argv[0].lower():
            # This code is loading in a celery server - Don't start the actual flask app.
            log.info("Running in a Celery worker - Not starting the Flask app")
            return

        # Initialize monitoring, if any is defined
        monitor_init(app=app, config=conf)

        if os.path.basename(sys.argv[0]) == 'gunicorn':
            # Gunicorn takes care of spawning workers
            log.info("Running in Gunicorn - Not starting the Flask app")
            return

        # Debug mode is the default when not running via gunicorn
        app.debug = self.debug

        app.run(host='0.0.0.0', port=self.port)
222009
def start(self):
        
        plugins = voltron.plugin.pm.web_plugins
        self.app = DispatcherMiddleware(
            RootFlaskApp(),
            {
                "/api": APIFlaskApp(server=self),
                "/view": SharedDataMiddleware(
                    None,
                    {'/{}'.format(n): os.path.join(p._dir, 'static') for (n, p) in six.iteritems(plugins)}
                ),
                "/ui": ui_app
            }
        )

        def run_listener(name, cls, arg):
            # with pysigset.suspended_signals(signal.SIGCHLD):
            log.debug("Starting listener for {} socket on {}".format(name, str(arg)))
            s = cls(*arg)
            t = threading.Thread(target=s.serve_forever)
            t.daemon = True
            t.start()
            self.threads.append(t)
            self.listeners.append(s)

        if voltron.config.server.listen.tcp:
            run_listener('tcp', ThreadedVoltronWSGIServer, list(voltron.config.server.listen.tcp) + [self.app])

        if voltron.config.server.listen.domain and sys.platform != 'win32':
            path = os.path.expanduser(str(voltron.config.server.listen.domain))
            try:
                os.unlink(path)
            except:
                pass
            run_listener('domain', ThreadedUnixWSGIServer, [path, self.app])

        self.is_running = True
1014349
function loadApis() {
  // Shortcut if apis already have been loaded
  if (apis !== undefined) {
    return Promise.resolve(apis);
  }

  const apiSpecsPath = path.join(process.cwd(), plugin.config.apisPath);

  // This event allows to inject code before loading all APIs
  return plugin.myrmex.fire('beforeApisLoad')
  .then(() => {
    // Retrieve configuration path of all API specifications
    return Promise.promisify(fs.readdir)(apiSpecsPath);
  })
  .then(subdirs => {
    // Load all the API specifications
    const apiPromises = [];
    _.forEach(subdirs, (subdir) => {
      const apiSpecPath = path.join(apiSpecsPath, subdir, 'spec');
      // subdir is the identifier of the API, so we pass it as the second argument
      apiPromises.push(loadApi(apiSpecPath, subdir));
    });
    return Promise.all(apiPromises);
  })
  .then(apis => {
    // This event allows to inject code to add or delete or alter API specifications
    return plugin.myrmex.fire('afterApisLoad', apis);
  })
  .spread(loadedApis => {
    apis = loadedApis;
    return Promise.resolve(apis);
  })
  .catch(e => {
    if (e.code === 'ENOENT' && path.basename(e.path) === path.basename(plugin.config.apisPath)) {
      return Promise.resolve([]);
    }
    return Promise.reject(e);
  });
}
149604
def load_jupyter_server_extension(nb_server_app):
  """"""
  app = nb_server_app.web_app
  host_pattern = '.*$'

  app.add_handlers(host_pattern, [
      (utils.url_path_join(app.settings['base_url'], '/http_over_websocket'),
       handlers.HttpOverWebSocketHandler),
      (utils.url_path_join(app.settings['base_url'],
                           '/http_over_websocket/diagnose'),
       handlers.HttpOverWebSocketDiagnosticHandler),
  ])
  print('jupyter_http_over_ws extension initialized. Listening on '
        '/http_over_websocket')
633622
def require_app(app_name, api_style=False):
    
    iterable = (inspect.getmodule(frame[0]) for frame in inspect.stack())
    modules = [module for module in iterable if module is not None]
    if api_style:
        m = modules[2]  # skip a frame for "api" module
    else:
        m = modules[1]
    m._REQUIRED_APP = getattr(m, '_REQUIRED_APP', [])
    m._REQUIRED_APP.append(app_name)
    LOG.debug('require_app: %s is required by %s', app_name, m.__name__)
411111
def init_app(event_source, *, loop=None):
    

    dispatcher = Dispatcher(event_source)

    # Schedule the dispatcher
    loop.create_task(dispatcher.publish())

    app = web.Application(loop=loop)
    app['dispatcher'] = dispatcher
    app.router.add_get(EVENTS_ENDPOINT, websocket_handler)
    return app
1337643
function startAppServer(fn) {
  if (!checkingAppServerPort) {
    server = fork(appServer.file, [], appServer.options);
    server.on('exit', code => {
      checkingAppServerPort = false;
      server.removeAllListeners();
      server = null;
      fn(Error('failed to start server'));
    });

    checkingAppServerPort = true;
    waitForPortOpen(appServer.port, fn);
  }
}
166799
def run(self):
        """"""
        for wsock in self.wsocks:
            wsock.run()
        for api in self.apis:
            api.run()
814363
def start(self):
        
        #: Schedule a load view if given and remote debugging is not active
        #: the remote debugging init call this after dev connection is ready
        if self.load_view and self.dev != "remote":
            self.deferred_call(self.load_view, self)

        self.loop.start()
1318377
def start_rest_api(host, port, connection, timeout, registry,
                   client_max_size=None):
    
    loop = asyncio.get_event_loop()
    connection.open()
    app = web.Application(loop=loop, client_max_size=client_max_size)
    app.on_cleanup.append(lambda app: connection.close())

    # Add routes to the web app
    LOGGER.info('Creating handlers for validator at %s', connection.url)

    handler = RouteHandler(loop, connection, timeout, registry)

    app.router.add_post('/batches', handler.submit_batches)
    app.router.add_get('/batch_statuses', handler.list_statuses)
    app.router.add_post('/batch_statuses', handler.list_statuses)

    app.router.add_get('/state', handler.list_state)
    app.router.add_get('/state/{address}', handler.fetch_state)

    app.router.add_get('/blocks', handler.list_blocks)
    app.router.add_get('/blocks/{block_id}', handler.fetch_block)

    app.router.add_get('/batches', handler.list_batches)
    app.router.add_get('/batches/{batch_id}', handler.fetch_batch)

    app.router.add_get('/transactions', handler.list_transactions)
    app.router.add_get(
        '/transactions/{transaction_id}',
        handler.fetch_transaction)

    app.router.add_get('/receipts', handler.list_receipts)
    app.router.add_post('/receipts', handler.list_receipts)

    app.router.add_get('/peers', handler.fetch_peers)
    app.router.add_get('/status', handler.fetch_status)

    subscriber_handler = StateDeltaSubscriberHandler(connection)
    app.router.add_get('/subscriptions', subscriber_handler.subscriptions)
    app.on_shutdown.append(lambda app: subscriber_handler.on_shutdown())

    # Start app
    LOGGER.info('Starting REST API on %s:%s', host, port)

    web.run_app(
        app,
        host=host,
        port=port,
        access_log=LOGGER,
        access_log_format='%r: %s status, %b size, in %Tf s')
163218
def start(self, app):
        
        app.middlewares.insert(0, debugtoolbar_middleware_factory)
        self.global_panels = [Panel(self.app) for Panel in self.cfg.global_panels]
788399
def run(app: web.Application):
    
    host = app['config']['host']
    port = app['config']['port']

    # starts app. run_app() will automatically start the async context.
    web.run_app(app, host=host, port=port)
806919
def init_app(self, app):
        """"""
        # Set default Flask config option.
        app.config.setdefault('STATICS_MINIFY', False)

        # Select resources.
        self.all_resources = ALL_RESOURCES_MINIFIED if app.config.get('STATICS_MINIFY') else ALL_RESOURCES
        self.all_variables = ALL_VARIABLES

        # Add this instance to app.extensions.
        if not hasattr(app, 'extensions'):
            app.extensions = dict()
        if 'statics' in app.extensions:
            raise ValueError('Already registered extension STATICS.')
        app.extensions['statics'] = _StaticsState(self, app)

        # Initialize blueprint.
        name = 'flask_statics_helper'
        static_url_path = '{0}/{1}'.format(app.static_url_path, name)
        self.blueprint = Blueprint(name, __name__, template_folder='templates', static_folder='static',
                                   static_url_path=static_url_path)
        self.blueprint.add_app_template_global(self.all_variables, '_flask_statics_helper_all_variables')
        self.blueprint.add_app_template_global(self.all_resources, '_flask_statics_helper_all_resources')
        app.register_blueprint(self.blueprint)
1145753
def app_create(self, data, **kwargs):
        ""
        api_path = "/api/v2/apps.json"
        return self.call(api_path, method="POST", data=data, **kwargs)
427978
def initialize(g, app):
    

    if 'DATABASES' in app.config and 'REDIS' in app.config['DATABASES']:

        # Initialize connections for console commands
        for k, v in app.config['DATABASES']['REDIS'].items():
            init_db_conn(k, **v)

        @app.before_request
        def before_request():
            """
            Assign redis connection pool to the global
            flask object at the beginning of every request
            """
            for k, v in app.config['DATABASES']['REDIS'].items():
                init_db_conn(k, **v)
            g.redis_pool = redis_pool

        if 'test' not in sys.argv:
            @app.teardown_request
            def teardown_request(exception):
                pool = getattr(g, 'redis_pool', None)
                if pool is not None:
                    pool.close()
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)
1019557
def start
      setup_signal_handlers
      @server = WEBrick::HTTPServer.new(options)
      @server.mount '/', Rack::Handler::WEBrick, app
      @server.start
    end