How to use the aiohttp.web.AppRunner function in aiohttp

To help you get started, we’ve selected a few aiohttp examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github MagicStack / uvloop / tests / test_aiohttp.py View on Github external
request.app['websockets'].discard(ws)
            return ws

        async def on_shutdown(app):
            for ws in set(app['websockets']):
                await ws.close(
                    code=aiohttp.WSCloseCode.GOING_AWAY,
                    message='Server shutdown')

        asyncio.set_event_loop(self.loop)
        app = aiohttp.web.Application()
        app.router.add_get('/', websocket_handler)
        app.on_shutdown.append(on_shutdown)
        app['websockets'] = weakref.WeakSet()

        runner = aiohttp.web.AppRunner(app)
        self.loop.run_until_complete(runner.setup())
        site = aiohttp.web.TCPSite(runner, '0.0.0.0', '0')
        self.loop.run_until_complete(site.start())
        port = site._server.sockets[0].getsockname()[1]

        async def client():
            async with aiohttp.ClientSession() as client:
                async with client.ws_connect(
                        'http://127.0.0.1:{}'.format(port)) as ws:
                    await ws.send_str("hello")
                    async for msg in ws:
                        assert msg.data == "hello"

        client_task = asyncio.ensure_future(client())

        async def stop():
github aio-libs / aiohttp-remotes / tests / test_cloudfare.py View on Github external
async def start(self):
        port = unused_port()
        self.runner = web.AppRunner(self.app)
        await self.runner.setup()
        site = web.TCPSite(self.runner, '127.0.0.1', port,
                           ssl_context=self.ssl_context)
        await site.start()
        return {'www.cloudflare.com': port}
github pengutronix / aiohttp-json-rpc / tests / test_django_transactions.py View on Github external
patch_db_connections()

    # just to be sure
    assert Item.objects.count() == 0

    # setup rpc
    app = Application()
    rpc = JsonRpc()

    rpc.add_methods(
        ('', add),
    )

    app.router.add_route('*', '/', rpc.handle_request)

    runner = AppRunner(app)
    await runner.setup()
    site = TCPSite(runner, 'localhost', unused_tcp_port)
    await site.start()

    # setup clients and watchdog
    tasks = [
        create_client(1, list(range(0, 10))),
        create_client(2, list(range(2, 5)), sleep=0.2),
    ]

    tasks = [
        *tasks,
        asyncio.ensure_future(watchdog(tasks)),
    ]

    # run
github henry232323 / RPGBot / pyhtml / server.py View on Github external
async def host(self):  # Start the connection to the DB and then start the Kyoukai server
        await self.bot.db.connect()
        await self.connect()
        # asyncio.ensure_future(eval.repl(self))

        runner = web.AppRunner(self)
        await runner.setup()
        site = web.TCPSite(runner, '0.0.0.0', 6667)
        await site.start()
github home-assistant / hassio-supervisor / hassio / api / __init__.py View on Github external
def __init__(self, coresys: CoreSys):
        """Initialize Docker base wrapper."""
        self.coresys: CoreSys = coresys
        self.security: SecurityMiddleware = SecurityMiddleware(coresys)
        self.webapp: web.Application = web.Application(
            middlewares=[self.security.token_validation]
        )

        # service stuff
        self._runner: web.AppRunner = web.AppRunner(self.webapp)
        self._site: Optional[web.TCPSite] = None
github opsdroid / opsdroid / opsdroid / web.py View on Github external
def __init__(self, opsdroid):
        """Create web object."""
        self.opsdroid = opsdroid
        try:
            self.config = self.opsdroid.config["web"]
        except KeyError:
            self.config = {}
        self.web_app = web.Application()
        self.runner = web.AppRunner(self.web_app)
        self.site = None
        self.web_app.router.add_get("/", self.web_index_handler)
        self.web_app.router.add_get("", self.web_index_handler)
        self.web_app.router.add_get("/stats", self.web_stats_handler)
        self.web_app.router.add_get("/stats/", self.web_stats_handler)
github ekonda / sketal / bot.py View on Github external
def callback_run(self, custom_process=False):
        host = getenv('IP', '127.0.0.1')
        port = int(getenv('PORT', 8000))

        self.logger.info("Started to process messages")

        try:
            app = web.Application()
            app.router.add_post('/', self.callback_processor)

            runner = web.AppRunner(app)
            self.loop.run_until_complete(runner.setup())

            site = web.TCPSite(runner, host, port)
            self.loop.run_until_complete(site.start())

        except OSError:
            self.logger.error("Address already in use: " + str(host) + ":" + str(port))
            return

        task = self.add_task(Future())

        if custom_process:
            return task

        print("======== Running on http://{}:{} ========\n"
              "         (Press CTRL+C to quit)".format(*server.sockets[0].getsockname()))
github virtool / virtool / virtool / app.py View on Github external
async def create_app_runner(app: web.Application, host: str, port: int) -> web.AppRunner:
    """
    Create an :class:`aiohttp.web.AppRunner` to allow customization of signal handlers.

    The basic :func:`aiohttp.web.run_app` sets up handlers for `SIGINT` and `SIGTERM` that can interfere with Virtool
    code such as that for restarting the server after software update. This custom runner allows handling of signals
    as well as restart and shutdown events from users.

    https://docs.aiohttp.org/en/stable/web_advanced.html#application-runners

    :param app: the application
    :param host: the host to listen on
    :param port: the port to listen on
    :return: a custom :class:`~aiohttp.web.AppRunner`

    """
    runner = web.AppRunner(app)
github virtool / virtool / virtool / app.py View on Github external
"""
    Create an :class:`aiohttp.web.AppRunner` to allow customization of signal handlers.

    The basic :func:`aiohttp.web.run_app` sets up handlers for `SIGINT` and `SIGTERM` that can interfere with Virtool
    code such as that for restarting the server after software update. This custom runner allows handling of signals
    as well as restart and shutdown events from users.

    https://docs.aiohttp.org/en/stable/web_advanced.html#application-runners

    :param app: the application
    :param host: the host to listen on
    :param port: the port to listen on
    :return: a custom :class:`~aiohttp.web.AppRunner`

    """
    runner = web.AppRunner(app)

    await runner.setup()

    site = web.TCPSite(runner, host, port)

    await site.start()

    logger.info(f"Listening at http://{host}:{port}")

    return runner
github lablup / backend.ai-agent / src / ai / backend / agent / watcher.py View on Github external
token = 'insecure'
    log.debug('watcher authentication token: {}', token)
    app['token'] = token

    app.middlewares.append(auth_middleware)
    app.on_shutdown.append(shutdown_app)
    app.on_startup.append(init_app)
    app.on_response_prepare.append(prepare_hook)
    ssl_ctx = None
    if app['config']['watcher']['ssl-enabled']:
        ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
        ssl_ctx.load_cert_chain(
            str(app['config']['watcher']['ssl-cert']),
            str(app['config']['watcher']['ssl-privkey']),
        )
    runner = web.AppRunner(app)
    await runner.setup()
    watcher_addr = app['config']['watcher']['service-addr']
    site = web.TCPSite(
        runner,
        str(watcher_addr.host),
        watcher_addr.port,
        backlog=5,
        reuse_port=True,
        ssl_context=ssl_ctx,
    )
    await site.start()
    log.info('started at {}', watcher_addr)
    try:
        stop_sig = yield
    finally:
        log.info('shutting down...')