Python aiohttp.web.TCPSite() Examples

The following are 30 code examples of aiohttp.web.TCPSite(). 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: 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 #2
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 #3
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 #4
Source File: cli.py    From dffml with MIT License 6 votes vote down vote up
def start(self):
        if self.insecure:
            self.site = web.TCPSite(
                self.runner, host=self.addr, port=self.port
            )
        else:
            ssl_context = ssl.create_default_context(
                purpose=ssl.Purpose.SERVER_AUTH, cafile=self.cert
            )
            ssl_context.load_cert_chain(self.cert, self.key)
            self.site = web.TCPSite(
                self.runner,
                host=self.addr,
                port=self.port,
                ssl_context=ssl_context,
            )
        await self.site.start()
        self.port = self.site._server.sockets[0].getsockname()[1]
        self.logger.info(f"Serving on {self.addr}:{self.port}") 
Example #5
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 #6
Source File: test_confserver.py    From bumper with GNU General Public License v3.0 6 votes vote down vote up
def test_confserver_exceptions():
    with LogCapture() as l:

            conf_server = bumper.ConfServer(("127.0.0.1", 8007), usessl=True)
            conf_server.confserver_app()        
            conf_server.site = web.TCPSite

            #bind permission       
            conf_server.site.start = mock.Mock(side_effect=OSError(1, "error while attempting to bind on address ('127.0.0.1', 8007): permission denied"))
            await conf_server.start_server()

            #asyncio Cancel
            conf_server.site = web.TCPSite
            conf_server.site.start = mock.Mock(side_effect=asyncio.CancelledError)
            await conf_server.start_server()

            #general exception
            conf_server.site = web.TCPSite
            conf_server.site.start = mock.Mock(side_effect=Exception(1, "general"))
            await conf_server.start_server()
    
    l.check_present(
        ("confserver", "ERROR", "error while attempting to bind on address ('127.0.0.1', 8007): permission denied")
    ) 
Example #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
Source File: server.py    From pyatv with MIT License 5 votes vote down vote up
def start(self):
        """Start the web server."""
        if not self._port:
            self._port = unused_port()

        _LOGGER.debug("Starting AirPlay file server on port %d", self._port)
        await self.runner.setup()
        self.site = web.TCPSite(self.runner, str(self._address), self._port)
        await self.site.start() 
Example #15
Source File: http.py    From async-worker with MIT License 5 votes vote down vote up
def startup(self, app):
        app[RouteTypes.HTTP] = {}
        routes = app.routes_registry.http_routes

        app[RouteTypes.HTTP]["app"] = http_app = web.Application(
            middlewares=(http_metrics_middleware,)
        )

        for route in routes:
            for route_def in route.aiohttp_routes():
                route_def.register(http_app.router)

        if settings.METRICS_ROUTE_ENABLED:
            http_app.router.add_route(
                method="GET",
                path=settings.METRICS_ROUTE_PATH,
                handler=metrics_route_handler,
            )

        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 #16
Source File: pairing.py    From pyatv with MIT License 5 votes vote down vote up
def begin(self):
        """Start the pairing server and publish service."""
        port = unused_port()

        await self.runner.setup()
        self.site = web.TCPSite(self.runner, "0.0.0.0", port)
        await self.site.start()

        _LOGGER.debug("Started pairing web server at port %d", port)

        for ipaddr in _get_private_ip_addresses():
            await self._publish_service(ipaddr, port) 
Example #17
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 #18
Source File: appv2.py    From code-jam-5 with MIT License 5 votes vote down vote up
def webs():
    try:
        await runner.setup()
        site = web.TCPSite(runner, HOST, PORT)
        await site.start()
    except Exception:
        await runner.cleanup()
        raise 
Example #19
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 #20
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 #21
Source File: http_echo.py    From Hands-On-Reactive-Programming-with-Python with MIT License 5 votes vote down vote up
def start_server(runner):
    await runner.setup()
    site = web.TCPSite(runner, 'localhost', 8080)
    await site.start() 
Example #22
Source File: async_views.py    From jupyter-plotly-dash with GNU Affero General Public License v3.0 5 votes vote down vote up
def launch_it(self, app, port):
        runner = web.AppRunner(app)
        await runner.setup()
        site = web.TCPSite(runner, 'localhost', port)
        await site.start()
        return runner, site 
Example #23
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 #24
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 #25
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 #26
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 #27
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 #28
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 #29
Source File: test_comment_commands.py    From lbry-sdk with MIT License 5 votes vote down vote up
def start(self):
        self.runner = web.AppRunner(self.app)
        await self.runner.setup()
        self.server = web.TCPSite(self.runner, 'localhost', self.port)
        await self.server.start() 
Example #30
Source File: websocket.py    From lbry-sdk with MIT License 5 votes vote down vote up
def start(self):
        await self.runner.setup()
        await TCPSite(self.runner, self.manager.env.websocket_host, self.manager.env.websocket_port).start()