Python aiohttp.web.AppRunner() Examples

The following are 30 code examples of aiohttp.web.AppRunner(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module aiohttp.web , or try the search function .
Example #1
Source File: test_http.py    From async-worker with MIT License 6 votes vote down vote up
def test_startup_initializes_an_web_application(self, start):
        self.app.routes_registry = self.routes_registry

        await self.signal_handler.startup(self.app)

        self.assertIsInstance(self.app[RouteTypes.HTTP]["app"], web.Application)
        self.assertIsInstance(
            self.app[RouteTypes.HTTP]["runner"], web.AppRunner
        )
        site: web.TCPSite = self.app[RouteTypes.HTTP]["site"]
        self.assertIsInstance(site, web.TCPSite)

        self.assertEqual(site._port, settings.HTTP_PORT)
        self.assertEqual(site._host, settings.HTTP_HOST)

        start.assert_awaited_once() 
Example #2
Source File: jsonrpc.py    From pyquarkchain with MIT License 6 votes vote down vote up
def start(self):
        app = web.Application(client_max_size=JSON_RPC_CLIENT_REQUEST_MAX_SIZE)
        cors = aiohttp_cors.setup(app)
        route = app.router.add_post("/", self.__handle)
        cors.add(
            route,
            {
                "*": aiohttp_cors.ResourceOptions(
                    allow_credentials=True,
                    expose_headers=("X-Custom-Server-Header",),
                    allow_methods=["POST", "PUT"],
                    allow_headers=("X-Requested-With", "Content-Type"),
                )
            },
        )
        self.runner = web.AppRunner(app, access_log=None)
        self.loop.run_until_complete(self.runner.setup())
        site = web.TCPSite(self.runner, self.host, self.port)
        self.loop.run_until_complete(site.start()) 
Example #3
Source File: server.py    From maubot with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, management_api: web.Application, config: Config,
                 loop: asyncio.AbstractEventLoop) -> None:
        self.loop = loop or asyncio.get_event_loop()
        self.app = web.Application(loop=self.loop, client_max_size=100 * 1024 * 1024)
        self.config = config

        self.setup_appservice()
        self.app.add_subapp(config["server.base_path"], management_api)
        self.setup_instance_subapps()
        self.setup_management_ui()

        self.runner = web.AppRunner(self.app, access_log_class=AccessLogger) 
Example #4
Source File: ws.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def start(self) -> None:
        """
        Start this transport.

        Raises:
            InboundTransportSetupError: If there was an error starting the webserver

        """
        app = await self.make_application()
        runner = web.AppRunner(app)
        await runner.setup()
        self.site = web.TCPSite(runner, host=self.host, port=self.port)
        try:
            await self.site.start()
        except OSError:
            raise InboundTransportSetupError(
                "Unable to start websocket server with host "
                + f"'{self.host}' and port '{self.port}'\n"
            ) 
Example #5
Source File: http.py    From aries-cloudagent-python with Apache License 2.0 6 votes vote down vote up
def start(self) -> None:
        """
        Start this transport.

        Raises:
            InboundTransportSetupError: If there was an error starting the webserver

        """
        app = await self.make_application()
        runner = web.AppRunner(app)
        await runner.setup()
        self.site = web.TCPSite(runner, host=self.host, port=self.port)
        try:
            await self.site.start()
        except OSError:
            raise InboundTransportSetupError(
                "Unable to start webserver with host "
                + f"'{self.host}' and port '{self.port}'\n"
            ) 
Example #6
Source File: conftest.py    From aries-protocol-test-suite with Apache License 2.0 6 votes vote down vote up
def http_endpoint(config, suite):
    """Create http server task."""

    async def handle(request):
        """aiohttp handle POST."""
        response = []
        with suite.reply(response.append):
            await suite.handle(await request.read())

        if response:
            return web.Response(body=response.pop())

        raise web.HTTPAccepted()

    app = web.Application()
    app.router.add_post('/', handle)
    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, config['host'], config['port'])
    server_task = asyncio.ensure_future(site.start())
    yield
    server_task.cancel()
    with suppress(asyncio.CancelledError):
        await server_task
    await runner.cleanup() 
Example #7
Source File: app_aiohttp.py    From python-sensor with MIT License 6 votes vote down vote up
def run_server():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    app = web.Application(debug=False)
    app.add_routes([web.get('/', say_hello)])
    app.add_routes([web.get('/401', four_hundred_one)])
    app.add_routes([web.get('/500', five_hundred)])
    app.add_routes([web.get('/exception', raise_exception)])

    runner = web.AppRunner(app)
    loop.run_until_complete(runner.setup())
    site = web.TCPSite(runner, '127.0.0.1', testenv["aiohttp_port"])

    loop.run_until_complete(site.start())
    loop.run_forever() 
Example #8
Source File: confserver.py    From bumper with GNU General Public License v3.0 6 votes vote down vote up
def start_site(self, app, address='localhost', port=8080, usessl=False):
        runner = web.AppRunner(app)
        self.runners.append(runner)
        await runner.setup()
        if usessl:
            ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
            ssl_ctx.load_cert_chain(bumper.server_cert, bumper.server_key)
            site = web.TCPSite(
                runner,
                host=address,
                port=port,
                ssl_context=ssl_ctx,
            )

        else:
            site = web.TCPSite(
                runner, host=address, port=port
            )

        await site.start() 
Example #9
Source File: server.py    From snare with GNU General Public License v3.0 6 votes vote down vote up
def start(self):
        app = web.Application()
        app.add_routes([web.route('*', '/{tail:.*}', self.handle_request)])
        aiohttp_jinja2.setup(
            app, loader=jinja2.FileSystemLoader(self.dir)
        )
        middleware = SnareMiddleware(
            error_404=self.meta['/status_404'].get('hash'),
            headers=self.meta['/status_404'].get('headers', []),
            server_header=self.run_args.server_header
        )
        middleware.setup_middlewares(app)

        self.runner = web.AppRunner(app)
        await self.runner.setup()
        site = web.TCPSite(
            self.runner,
            self.run_args.host_ip,
            self.run_args.port)

        await site.start()
        names = sorted(str(s.name) for s in self.runner.sites)
        print("======== Running on {} ========\n"
              "(Press CTRL+C to quit)".format(', '.join(names))) 
Example #10
Source File: appservice.py    From mautrix-python with Mozilla Public License 2.0 6 votes vote down vote up
def start(self, host: str = "127.0.0.1", port: int = 8080) -> None:
        connector = None
        self.log.debug(f"Starting appservice web server on {host}:{port}")
        if self.server.startswith("https://") and not self.verify_ssl:
            connector = aiohttp.TCPConnector(verify_ssl=False)
        self._http_session = aiohttp.ClientSession(loop=self.loop, connector=connector)
        self._intent = AppServiceAPI(base_url=self.server, bot_mxid=self.bot_mxid, log=self.log,
                                     token=self.as_token, state_store=self.state_store,
                                     real_user_content_key=self.real_user_content_key,
                                     client_session=self._http_session).bot_intent()
        ssl_ctx = None
        if self.tls_cert and self.tls_key:
            ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
            ssl_ctx.load_cert_chain(self.tls_cert, self.tls_key)
        self.runner = web.AppRunner(self.app)
        await self.runner.setup()
        site = web.TCPSite(self.runner, host, port, ssl_context=ssl_ctx)
        await site.start() 
Example #11
Source File: client.py    From DBL-Python-Library with MIT License 6 votes vote down vote up
def webhook(self):
        async def vote_handler(request):
            req_auth = request.headers.get('Authorization')
            if self.webhook_auth == req_auth:
                data = await request.json()
                if data.get('type') == 'upvote':
                    event_name = 'dbl_vote'
                elif data.get('type') == 'test':
                    event_name = 'dbl_test'
                self.bot.dispatch(event_name, data)
                return web.Response()
            else:
                return web.Response(status=401)

        app = web.Application(loop=self.loop)
        app.router.add_post(self.webhook_path, vote_handler)
        runner = web.AppRunner(app)
        await runner.setup()
        self._webserver = web.TCPSite(runner, '0.0.0.0', self.webhook_port)
        await self._webserver.start() 
Example #12
Source File: pairing.py    From pyatv with MIT License 6 votes vote down vote up
def __init__(self, config, session_manager: ClientSessionManager, loop, **kwargs):
        """Initialize a new instance."""
        super().__init__(session_manager, config.get_service(Protocol.DMAP))
        self._loop = loop
        self._zeroconf = kwargs.get(
            "zeroconf", Zeroconf(loop, address_family=[netifaces.AF_INET])
        )
        self._name = kwargs.get("name", "pyatv")
        self.app = web.Application()
        self.app.router.add_routes([web.get("/pairing", self.handle_request)])
        self.runner = web.AppRunner(self.app)
        self.site = None
        self._pin_code = None
        self._has_paired = False
        self._pairing_guid = (
            kwargs.get("pairing_guid", None) or _generate_random_guid()
        )[2:].upper() 
Example #13
Source File: test_examples.py    From aries-staticagent-python with Apache License 2.0 6 votes vote down vote up
def listening_endpoint(connection, unused_tcp_port):
    """Create http server task."""

    async def handle(request):
        """aiohttp handle POST."""
        await connection.handle(await request.read())
        raise web.HTTPAccepted()

    app = web.Application()
    app.router.add_post('/', handle)
    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, 'localhost', unused_tcp_port)
    server_task = asyncio.ensure_future(site.start())
    yield 'http://localhost:{}'.format(unused_tcp_port)
    server_task.cancel()
    with suppress(asyncio.CancelledError):
        await server_task
    await runner.cleanup() 
Example #14
Source File: humming_web_app.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        if HummingWebApp.__instance is not None:
            raise Exception("This class is a singleton!")
        else:
            HummingWebApp.__instance = self
        self._ev_loop: None
        self._impl: Optional[web.Application] = None
        self._runner: Optional[web.AppRunner] = None
        self._started: bool = False
        self._stock_responses = []
        self.host = "127.0.0.1" 
Example #15
Source File: serve.py    From aiohttp-devtools with MIT License 5 votes vote down vote up
def start_main_app(config: Config, app_factory, loop):
    app = await config.load_app(app_factory)

    modify_main_app(app, config)

    await check_port_open(config.main_port, loop)
    runner = web.AppRunner(app, access_log_class=AccessLogger)
    await runner.setup()
    site = web.TCPSite(runner, host=HOST, port=config.main_port, shutdown_timeout=0.1)
    await site.start()
    return runner 
Example #16
Source File: humming_web_app.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def _start(self):
        try:
            HummingWebApp._port = get_open_port()
            self._impl: Optional[web.Application] = web.Application()
            self._impl.add_routes([web.route("*", '/{tail:.*}', self._handler)])
            self._runner = web.AppRunner(self._impl)
            await self._runner.setup()
            site = web.TCPSite(self._runner, host=HummingWebApp.host, port=HummingWebApp._port)
            await site.start()
            self._started = True
        except Exception:
            logging.error("oops!", exc_info=True) 
Example #17
Source File: test_proxies.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, **kwargs):
        self._port = random_port()
        self.proxy = Proxy(
            address="127.0.0.1:0",
            prefix="/foobar",
            gateway_address=f"127.0.0.1:{self._port}",
            log_level="debug",
            proxy_status_period=0.5,
            **kwargs,
        )
        self.app = web.Application()
        self.runner = web.AppRunner(self.app) 
Example #18
Source File: utils_test.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, routes=None, app=None, host="localhost", port=None):
        self.app = app or web.Application()
        if routes is not None:
            self.app.add_routes(routes)
        self.runner = web.AppRunner(self.app)
        self.host = host
        self.port = port or random_port() 
Example #19
Source File: app.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setup(self):
        # Register signal handlers
        loop = asyncio.get_event_loop()
        for s in (signal.SIGTERM, signal.SIGINT):
            loop.add_signal_handler(s, self.handle_shutdown_signal, s)

        # Start the authenticator
        await self.authenticator.setup(self.app)

        # Start the backend
        await self.backend.setup(self.app)

        # Start the aiohttp application
        self.runner = web.AppRunner(
            self.app,
            handle_signals=False,
            access_log_class=AccessLogger,
            access_log=self.log,
        )
        await self.runner.setup()

        host, port = self.address.split(":")
        port = int(port)
        site = web.TCPSite(self.runner, host, port, shutdown_timeout=15.0, backlog=128)
        await site.start()
        self.log.info("Dask-Gateway server started")
        self.log.info("- Private API server listening at http://%s", self.address) 
Example #20
Source File: server.py    From pyatv with MIT License 5 votes vote down vote up
def __init__(self, file_to_serve, address, port=None):
        """Initialize a new StaticFileWebServer."""
        self.path = pathlib.Path(file_to_serve)
        self.app = web.Application(middlewares=[self._middleware])
        self.app.router.add_static("/", self.path.parent, show_index=False)
        self.runner = web.AppRunner(self.app)
        self.site = None
        self._address = address  # Local address to bind to
        self._port = port 
Example #21
Source File: dmap.py    From pyatv with MIT License 5 votes vote down vote up
def start(self, start_web_server: bool):
        if start_web_server:
            self.port = unused_port()
            self.runner = web.AppRunner(self.app)
            await self.runner.setup()
            site = web.TCPSite(self.runner, "0.0.0.0", self.port)
            await site.start() 
Example #22
Source File: airplay.py    From pyatv with MIT License 5 votes vote down vote up
def start(self, start_web_server):
        if start_web_server:
            self.port = unused_port()
            self.runner = web.AppRunner(self.app)
            await self.runner.setup()
            site = web.TCPSite(self.runner, "0.0.0.0", self.port)
            await site.start() 
Example #23
Source File: server.py    From graham_discord_bot with MIT License 5 votes vote down vote up
def start(self):
        """Start the server"""
        runner = web.AppRunner(self.app, access_log = None if not config.Config.instance().debug else self.logger)
        await runner.setup()
        site = web.TCPSite(runner, self.host, self.port)
        await site.start() 
Example #24
Source File: fakeserver.py    From pubgate with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def start(self):
        self.port = port = unused_port()
        self.runner = web.AppRunner(self.app)
        await self.runner.setup()
        site = web.TCPSite(self.runner, '127.0.0.1', port)
        await site.start()
        return port 
Example #25
Source File: fakereqman.py    From reqman with GNU General Public License v2.0 5 votes vote down vote up
def run(self):
        print("> Fake Server:",self.root)

        async def start():
            runner = web.AppRunner(self.app)
            await runner.setup()
            self.site=web.TCPSite(runner, 'localhost', self.port)
            await self.site.start()
        
            while self._exit==False:
                await asyncio.sleep(0.333333)

            await self.site.stop()
            await runner.shutdown()

        asyncio.set_event_loop(asyncio.new_event_loop())
        loop=asyncio.get_event_loop()


        async def wait():
            while not isFree("127.0.0.1",self.port):
                await asyncio.sleep(0.5)

        loop.run_until_complete(wait()) 
        loop.run_until_complete(start())       
        loop.run_until_complete(wait()) 

        # gracefull death
        tasks = asyncio.all_tasks(loop) #py37
        for task in tasks: task.cancel()
        try:
            loop.run_until_complete(asyncio.gather(*tasks))
        except:
            pass
        loop.close() 
Example #26
Source File: resources_aiotransmission.py    From stig with GNU General Public License v3.0 5 votes vote down vote up
def start(self):
        self.runner = web.AppRunner(self.app)
        await self.runner.setup()
        site = web.TCPSite(self.runner, self.host, self.port)
        await site.start() 
Example #27
Source File: app.py    From asgard-api with MIT License 5 votes vote down vote up
def patched_startup(app):

    app[RouteTypes.HTTP] = {}
    routes = app.routes_registry.http_routes

    app[RouteTypes.HTTP]["app"] = http_app = web.Application()
    for route in routes:
        for route_def in route.aiohttp_routes():
            route_def.register(http_app.router)

    cors = aiohttp_cors.setup(
        http_app,
        defaults={
            "*": aiohttp_cors.ResourceOptions(
                allow_credentials=True, expose_headers="*", allow_headers="*"
            )
        },
    )

    # Configure CORS on all routes.
    for route in list(http_app.router.routes()):
        cors.add(route)

    app[RouteTypes.HTTP]["runner"] = web.AppRunner(http_app)
    await app[RouteTypes.HTTP]["runner"].setup()
    app[RouteTypes.HTTP]["site"] = web.TCPSite(
        runner=app[RouteTypes.HTTP]["runner"],
        host=settings.HTTP_HOST,
        port=settings.HTTP_PORT,
    )

    await app[RouteTypes.HTTP]["site"].start() 
Example #28
Source File: client.py    From hass-nabucasa with GNU General Public License v3.0 5 votes vote down vote up
def aiohttp_runner(self) -> web.AppRunner:
        """Return client webinterface aiohttp application.""" 
Example #29
Source File: server.py    From aries-cloudagent-python with Apache License 2.0 5 votes vote down vote up
def start(self) -> None:
        """
        Start the webserver.

        Raises:
            AdminSetupError: If there was an error starting the webserver

        """
        self.app = await self.make_application()
        runner = web.AppRunner(self.app)
        await runner.setup()

        plugin_registry: PluginRegistry = await self.context.inject(
            PluginRegistry, required=False
        )
        if plugin_registry:
            plugin_registry.post_process_routes(self.app)

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

        try:
            await self.site.start()
        except OSError:
            raise AdminSetupError(
                "Unable to start webserver with host "
                + f"'{self.host}' and port '{self.port}'\n"
            ) 
Example #30
Source File: statusserver.py    From piqueserver with GNU General Public License v3.0 5 votes vote down vote up
def listen(self):
        """Starts the status server on configured host/port"""
        app = self.create_app()
        logger = Logger() if logging_option.get() else None
        log_class = AccessLogger if logging_option.get() else None
        runner = web.AppRunner(app,
                               access_log=logger,
                               access_log_class=log_class)
        await as_deferred(runner.setup())
        site = web.TCPSite(runner, host_option.get(), port_option.get())
        await as_deferred(site.start())

        # TODO: explain why we do this
        await Deferred()