async def start(self): self.app.router.add_route("*", "/ws-rpc", self.handle_request) self.app.router.add_route("*", "/status", self.status) self.runner = AppRunner(self.app) await self.runner.setup() self.site = TCPSite(self.runner, self._host, self._port) await self.site.start()
async def run_bot(): app = Application() cors = aiohttp_cors.setup(app, defaults={ "*": aiohttp_cors.ResourceOptions( allow_credentials=True, expose_headers="*", allow_headers="*", ) }) app.add_routes(routes) for route in list(app.router.routes()): cors.add(route) runner = AppRunner(app) await runner.setup() with open("config.json") as conf: conf = json.load(conf) site = TCPSite(runner, conf["ip"], conf["port"]) bot = DiscordFoundry() app['bot'] = bot app['cors'] = cors await site.start() try: await bot.start(bot.config["token"]) except Exception: await bot.close(), raise finally: await runner.cleanup()
async def http_server(datadump, connection): # Create context for HTTP server app = Application() # Configure CORS options # Check https://github.com/aio-libs/aiohttp-cors for details cors_default_options = {} for host in WHITELIST: cors_default_options[host] = aiohttp_cors.ResourceOptions( allow_methods=['GET'], allow_headers=('Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'x-timebase', 'Link')) cors = aiohttp_cors.setup(app, defaults=cors_default_options) # Configure routes router = Router(datadump, connection) router.register(app.router) # Configure CORS on all routes for route in list(app.router.routes()): cors.add(route) runner = AppRunner(app) await runner.setup() site = TCPSite(runner, '0.0.0.0', HTTP_PORT) return runner, site
async def async_main(conf): async with AsyncExitStack() as stack: alert_webhooks = await stack.enter_async_context( AlertWebhooks(conf.alert_webhooks)) model = await stack.enter_async_context( get_model(conf, alert_webhooks=alert_webhooks)) alert_webhooks.set_model(model) app = Application() app['model'] = model app.router.add_routes(routes) GraphQLView.attach(app, route_path='/graphql', schema=graphql_schema, graphiql=True, enable_async=True, executor=GQLAIOExecutor()) runner = AppRunner(app) await runner.setup() host = conf.http_interface.bind_host port = conf.http_interface.bind_port site = TCPSite(runner, host, port) await site.start() stop_event = asyncio.Event() asyncio.get_running_loop().add_signal_handler(SIGINT, stop_event.set) asyncio.get_running_loop().add_signal_handler(SIGTERM, stop_event.set) logger.debug('Listening on http://%s:%s', host or 'localhost', port) await stop_event.wait() logger.debug('Cleanup...') t = asyncio.create_task(log_still_running_tasks()) await runner.cleanup() t.cancel() logger.debug('Cleanup done')
async def restart_webserver(self, *imports): ''' Stops the current running webserver and starts a new one Args: *imports: str A list of modules to import that contain a "routes" attribute ''' try: await self.web_runner.cleanup() except Exception as e: print("Error with closing previous server: ", e) # Make and link all the relevant options app = Application(loop=self.loop) for i in imports: x = import_module(i) app.add_routes(x.routes) app['bot'] = self # Run the site self.web_runner = AppRunner(app) await self.web_runner.setup() site = TCPSite(self.web_runner, self.commandline_args.host, self.commandline_args.port) await site.start() print( f"Server started: http://{self.commandline_args.host}:{self.commandline_args.port}/" )
def _new_transport_tcp(self) -> BaseSite: return TCPSite( self._runner, self.app.conf.web_bind, self.app.conf.web_port, ssl_context=self.app.conf.web_ssl_context, )
async def start_server_async(): runner = AppRunner(app) await runner.setup() site = TCPSite(runner, 'localhost', 7474) try: await site.start() except OSError as e: logger.warning(e)
async def run_async(self, host=None, port=None, loop=None): wsgi = WSGIHandler(application=self, loop=loop) app = Application(loop=loop) app.router.add_route("*", "/{path_info:.*}", wsgi) runner = AppRunner(app) await runner.setup() site = TCPSite(runner, host, port) await site.start()
async def run_server(): """Для запуска вне контейнера.""" app: Application = await http_app_factory() runner: AppRunner = AppRunner(app) await runner.setup() site: TCPSite = TCPSite(runner, 'localhost', 8080) await site.start() await runner.cleanup()
async def server_context(app: Application, port: int): log_format = '%s %r (%b) %Tfs' runner = AppRunner(app, access_log_format=log_format) await runner.setup() try: site = TCPSite(runner, port=port) await site.start() yield finally: await runner.cleanup()
async def main(loop=None): intent_controller = IntentController(model) application = Application(middlewares=[middleware.logging], logger=logger) application.router.add_post('/api/intent', intent_controller.post) runner = AppRunner(application) await runner.setup() site = TCPSite(runner, environ['APP_HOST'], int(environ['APP_PORT'])) await site.start()
async def run(self): runner = AppRunner(self._web_app) await runner.setup() host = self._config.get('http.host') port = self._config.get('http.port') site = TCPSite(runner, host, port) logging.info("Running nanobrew on %s:%d" % (host, port)) await site.start()
def configure(self, value: http_pb2.Server) -> None: assert isinstance(value, http_pb2.Server), type(value) self._app.middlewares.append(_healthcheck_middleware) self._app.middlewares.append(_opentracing_middleware) self._runner = AppRunner(self._app, access_log=self._access_log) self._site_factory = lambda: TCPSite( self._runner, value.bind.host, value.bind.port, )
def _create_site(self) -> Optional[Union[TCPSite, UnixSite]]: site = None transport = self.app.conf.web_transport.scheme if transport == 'tcp': site = TCPSite(self._runner, self.app.conf.web_bind, self.app.conf.web_port) elif transport == 'unix': site = UnixSite(self._runner, self.app.conf.web_transport.path) return site
async def run(self): runner = AppRunner(self.web_app) await runner.setup() # @TODO Get this from config. host = "0.0.0.0" port = 5300 site = TCPSite(runner, host, port) logging.info("Running nanobrew on %s:%d" % (host, port)) await site.start()
async def main(loop=None): recognize_controller = ResolverController(intents, ner, topic) application = Application(middlewares=[middleware.logging], logger=logger) application.router.add_post('/api/recognize', recognize_controller.post) runner = AppRunner(application) await runner.setup() site = TCPSite(runner, environ['APP_HOST'], int(environ['APP_PORT'])) await site.start()
async def create_app_server_once( app: Application, *, host: str = "127.0.0.1", port: int = 8080 ) -> AsyncIterator[URL]: runner = AppRunner(app, access_log=None) try: await runner.setup() site = TCPSite(runner, host, port, shutdown_timeout=0.0) await site.start() yield URL(site.name) finally: await runner.shutdown() await runner.cleanup()
async def async_main(conf): async with ClientSession() as session: current_alerts = await wait_for(retrieve_alerts(conf, session), 30) assert isinstance(current_alerts, list) logger.debug('Initial alerts:\n%s', '\n'.join(json.dumps(a) for a in current_alerts)) notify_aux = None app = Application() app['conf'] = conf app['current_alerts'] = current_alerts app['client_session'] = session app.router.add_routes(routes) runner = AppRunner(app) await runner.setup() try: site = TCPSite(runner, conf.bind_host, conf.bind_port) await site.start() logger.info('Listening on http://%s:%s', conf.bind_host, conf.bind_port) await setup_telegram_webhook(conf, session) while True: await sleep(conf.sleep_interval) try: new_alerts = await wait_for(retrieve_alerts(conf, session), 60) except Exception as e: logger.info('Failed to retrieve alerts: %s', e) await sleep(60) continue if {a['alertId'] for a in new_alerts } != {a['alertId'] for a in current_alerts}: logger.debug('Retrieved alerts:\n%s', '\n'.join(json.dumps(a) for a in new_alerts)) notify_aux = await notify_about_alerts(conf, session, current_alerts, new_alerts, notify_aux) current_alerts[:] = new_alerts except CancelledError: pass except Exception as e: logger.exception('async_main failed: %r', e) await tg_request( conf, session, 'sendMessage', { 'chat_id': conf.telegram_chat_id, 'text': f'\U0001F4A5 Exception: `{tg_md2_escape(repr(e))}`', 'parse_mode': 'MarkdownV2', }) finally: await runner.cleanup()
def buildSite(self): self.__site = TCPSite(self.__runner, host=self.__config.get_host(), port=self.__config.get_port(), shutdown_timeout=int( float(self.__config.get_shutdown_timeout())), backlog=self.__config.get_backlog(), reuse_address=self.__config.get_reuse_address(), reuse_port=self.__config.get_reuse_port()) self.logger.log( 1000, 'TCPSite Listening on {}:{}'.format(self.__config.get_host(), self.__config.get_port()))
async def main(loop=None): message_controller = MessageController(recognizer) search_controller = SearchController(db) application = Application(middlewares=[middleware.logging], logger=logger) application.router.add_post('/api/messages', message_controller.post) application.router.add_get('/api/search', search_controller.search) runner = AppRunner(application) await runner.setup() site = TCPSite(runner, environ['APP_HOST'], int(environ['APP_PORT'])) await site.start()
async def on_ready(): logger.info("\nLogged in as:\n{0} (ID: {0.id})".format(bot.user)) app = Application() app.add_routes(routes) # Pass bot to webserver app["bot"] = bot runner = AppRunner(app) await runner.setup() site = TCPSite(runner, "0.0.0.0", 9080) await site.start()
async def root_url(event_loop): application = build_app() runner = AppRunner(application) await runner.setup() site = TCPSite(runner, "127.0.0.1", 0) await site.start() try: for socket in site._server.sockets: host, port = socket.getsockname() break yield f"http://{host}:{port}" finally: await runner.cleanup()
async def _create_test_web_server_core() -> _TestWebServerCore: calls = [] app = Application(middlewares=[_get_test_middleware(calls)]) app.router.add_static('/static/', _dir_path) app.router.add_get('/dynamic/test4.txt', _handle_test4) app.router.add_get('/dynamic/test5.txt', _handle_test5) app.router.add_get('/dynamic/test6.txt', _handle_test6) runner = AppRunner(app) await runner.setup() host = 'localhost' port = unused_port() site = TCPSite(runner, host, port) await site.start() return _TestWebServerCore(host, port, calls, runner, site)
async def start(self): """ Setup and start API application. """ runner = AppRunner(self.app) await runner.setup() api_server = TCPSite(runner, host=self._listen_addr, port=self._listen_port) log.info("Starting API server...") try: await api_server.start() except BaseException: await runner.cleanup()
async def main(): host = '127.0.0.1' port = 8080 server = Server(proxy_handler) runner = ServerRunner(server) await runner.setup() site = TCPSite(runner, host, port) await site.start() print( f'============== Serving on http://{host}:{port}/ ===================') # pause here for serving while True: await sleep(100 * 3600)
async def start(self): if self._started: return self._started = True logger.info("Starting with webhook...") runner = ServerRunner(Server(self.__handler)) await runner.setup() self._srv = TCPSite(runner, self._host, self._port) logger.info("Listening on http://%s:%s%s", self._host, self._port, self._base_path) await self._srv.start() logger.info("Running!")
async def async_main(args): app = Application() app.add_routes(routes) # GraphQLView source: https://github.com/graphql-python/graphql-server/blob/master/graphql_server/aiohttp/graphqlview.py GraphQLView.attach(app, schema=schema, route_path='/api/graphql', graphiql=True, enable_async=True) runner = AppRunner(app) await runner.setup() try: site = TCPSite(runner, 'localhost', args.port) await site.start() logger.info(f'Listening on http://127.0.0.1:{args.port}') while True: await asyncio.sleep(10) finally: await runner.cleanup()
async def start_web_endpoint(config: 'Configuration', integration_context: 'IntegrationContext'): LOG.info('Starting web endpoint...') web_coros = [] # prepare the web application app = Application(client_max_size=CLIENT_MAX_SIZE) jwt = None # type: Optional[JWTValidator] if config.jwks_url: LOG.info('JWKS URL: %r', config.jwks_url) jwt = JWTValidator(jwks_urls=[config.jwks_url]) web_coros.append(ensure_future(jwt.poll())) else: LOG.warn( 'No JWKS URL Available, all requests requiring authorization will be rejected.' ) auth_handler = AuthHandler(config, jwt) await auth_handler.setup(app) app.add_routes(_build_control_routes(integration_context)) if integration_context.webhook_context: app.add_routes(integration_context.webhook_context.route_table) LOG.info('Starting web server on %s...', config.health_port) runner = AppRunner(app, access_log_class=IntegrationAccessLogger, access_log_format='%a %t "%r" %s %b') await runner.setup() site = TCPSite(runner, '0.0.0.0', config.health_port) web_coros.append(ensure_future(site.start())) LOG.info('...Web server started') return gather(*web_coros)
async def test_calling_httpx(unused_tcp_port: int, calculator_server_creator) -> None: """Test the httpx client.""" serv = calculator_server_creator(AioRequest) app = create_aiohttp_app(serv) runner = AppRunner(app) await runner.setup() site = TCPSite(runner, port=unused_tcp_port) await site.start() t = await create_client( Calculator, httpx_client_adapter(f"http://localhost:{unused_tcp_port}", timeout=1), ) r = await t.add(1, 2) assert r == 3 await runner.cleanup() await close_client(t)
async def on_ready(): bot.log(f"Logged in as {bot.user.name}: #{bot.user.id}.") try: channel = bot.get_channel( pickle.load(open(f"{bot.user.id}_restart.init", "rb"))) bot.log("Reinitialization complete.") await channel.send( f"⚡ Reinitialization complete ⚡\nCurrent version is **{bot.revision.current}**." ) os.remove(f"{bot.user.id}_restart.init") except FileNotFoundError: bot.log("Initialization complete.") # Initialize dashboard. if conf.dash.enabled: self.dash = Dash(bot) await self.dash.setup() self.dash_runner = AppRunner(self.dash.app) await self.dash_runner.setup() self.site = TCPSite(self.dash_runner, conf.dash.host, conf.dash.port) await self.site.start()