Python aiohttp.web.run_app() Examples

The following are 30 code examples of aiohttp.web.run_app(). 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: webserver_with_module.py    From aries-staticagent-python with Apache License 2.0 6 votes vote down vote up
def main():
    """Create connection and start web server."""
    args = config()
    conn = StaticConnection(
        (args.my_verkey, args.my_sigkey),
        their_vk=args.their_verkey,
        endpoint=args.endpoint,
    )

    bmc = BasicMessageCounter()
    conn.route_module(bmc)

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

    app = web.Application()
    app.add_routes([web.post('/', handle)])

    web.run_app(app, port=args.port) 
Example #2
Source File: app.py    From slim with zlib License 6 votes vote down vote up
def run(self, host, port):
        def reg(mine, target):
            assert isinstance(mine, Iterable)

            for i in mine:
                assert i, asyncio.Future

                async def dummy(_raw_app):
                    await i()
                target.append(dummy)

        reg(self.on_startup, self._raw_app.on_startup)
        reg(self.on_shutdown, self._raw_app.on_shutdown)
        reg(self.on_cleanup, self._raw_app.on_cleanup)

        self._prepare()
        web.run_app(host=host, port=port, app=self._raw_app) 
Example #3
Source File: main.py    From aiohttp-swagger3 with Apache License 2.0 6 votes vote down vote up
def main():
    app = web.Application()
    s = SwaggerDocs(
        app,
        title="Swagger Petstore",
        version="1.0.0",
        components="components.yaml",
        swagger_ui_settings=SwaggerUiSettings(path="/docs"),
    )
    s.add_routes(
        [
            web.get("/pets", get_all_pets),
            web.get("/pets/{pet_id}", get_one_pet),
            web.delete("/pets/{pet_id}", delete_one_pet),
            web.post("/pets", create_pet),
        ]
    )
    app["storage"] = {}
    web.run_app(app) 
Example #4
Source File: main.py    From aiohttp-swagger3 with Apache License 2.0 6 votes vote down vote up
def main():
    app = web.Application()
    s = SwaggerFile(
        app,
        spec_file="petstore.yaml",
        swagger_ui_settings=SwaggerUiSettings(path="/docs"),
    )
    s.add_routes(
        [
            web.get("/pets", get_all_pets),
            web.get("/pets/{pet_id}", get_one_pet),
            web.delete("/pets/{pet_id}", delete_one_pet),
            web.post("/pets", create_pet),
        ]
    )
    app["storage"] = {}
    web.run_app(app) 
Example #5
Source File: main.py    From aiohttp-swagger3 with Apache License 2.0 6 votes vote down vote up
def main():
    app = web.Application()
    s = SwaggerDocs(
        app,
        swagger_ui_settings=SwaggerUiSettings(
            path="/docs",
            layout="BaseLayout",
            deepLinking=False,
            displayOperationId=True,
            defaultModelsExpandDepth=5,
            defaultModelExpandDepth=5,
            defaultModelRendering="model",
            displayRequestDuration=True,
            docExpansion="list",
            filter=True,
            showExtensions=True,
            showCommonExtensions=True,
            supportedSubmitMethods=["get"],
            validatorUrl=None,
            withCredentials=True,
        ),
    )
    s.add_routes([web.get("/", handler, allow_head=True)])
    web.run_app(app) 
Example #6
Source File: server.py    From localstripe with GNU General Public License v3.0 6 votes vote down vote up
def start():
    parser = argparse.ArgumentParser()
    parser.add_argument('--port', type=int, default=8420)
    parser.add_argument('--from-scratch', action='store_true')
    args = parser.parse_args()

    if not args.from_scratch:
        store.try_load_from_disk()

    # Listen on both IPv4 and IPv6
    sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(('::', args.port))

    logger = logging.getLogger('aiohttp.access')
    logger.setLevel(logging.DEBUG)
    logger.addHandler(logging.StreamHandler())

    web.run_app(app, sock=sock, access_log=logger) 
Example #7
Source File: web_interface.py    From style_transfer with MIT License 6 votes vote down vote up
def run(self, port=8000):
        """Runs the web interface."""
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.loop)

        self.app = web.Application(middlewares=[IndexMiddleware()], loop=self.loop)
        self.app.event_queue = asyncio.Queue()
        self.app.image_encode_settings = {'format': 'png'}
        self.app.wss = []

        self.app.task_process_events = self.loop.create_task(process_events(self.app))

        self.app.router.add_route('GET', '/websocket', handle_websocket)
        self.app.router.add_static('/', STATIC_PATH)

        try:
            web.run_app(self.app, port=port, shutdown_timeout=1, handle_signals=False)
        except KeyboardInterrupt:
            pass 
Example #8
Source File: main.py    From aiohttp_apiset with Apache License 2.0 6 votes vote down vote up
def main():
    router = SwaggerRouter(
        swagger_ui='/swagger/',
        search_dirs=[BASE],
    )

    app = web.Application(
        router=router,
        middlewares=[jsonify],
    )
    router.set_cors(app, domains='*', headers=(
        (hdrs.ACCESS_CONTROL_EXPOSE_HEADERS, hdrs.AUTHORIZATION),
    ))

    # Include our specifications in a router,
    # is now available in the swagger-ui to the address http://localhost:8080/swagger/?spec=v1
    router.include(
        spec='swagger.yaml',
        operationId_mapping=opmap,
        name='v1',  # name to access in swagger-ui
    )

    web.run_app(app) 
Example #9
Source File: cli.py    From web3-gear with MIT License 6 votes vote down vote up
def run_server(host, port, endpoint, keystore, passcode, log, debug):
    try:
        response = requests.options(endpoint)
        response.raise_for_status()
    except requests.exceptions.ConnectionError:
        print("Unable to connect to Thor-Restful server.")
        return

    print(make_version())
    print("Listening on %s:%s" % (host, port))

    thor.set_endpoint(endpoint)
    if keystore == "":
        thor.set_accounts(solo())
    else:
        thor.set_accounts(_keystore(keystore, passcode))

    app = web.Application()
    app.router.add_post("/", lambda r: handle(r, log, debug))
    app.router.add_options("/", lambda r: web.Response(headers=res_headers))
    web.run_app(app, host=host, port=port) 
Example #10
Source File: signs_server.py    From concurrency2017 with MIT License 6 votes vote down vote up
def main(global_delay, local_delay, concurrency):
    global global_sleep, local_sleep, semaphore, index
    global_sleep = global_delay
    local_sleep = local_delay
    semaphore = asyncio.Semaphore(concurrency)
    print('Global delay =', global_delay)
    print('Local delay =', local_delay)
    print('Max. concurrency =', concurrency)
    print('Building inverted index...')
    index = build_index()

    app = web.Application()
    app.router.add_get('/', usage)
    app.router.add_get('/index/{word}', index_for)
    app.router.add_get('/name/{char}', char_name)

    print('Listening on port', PORT)
    web.run_app(app, port=PORT) 
Example #11
Source File: __init__.py    From py-walletconnect-bridge with GNU Lesser General Public License v3.0 6 votes vote down vote up
def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('--redis-use-sentinel', action='store_true')
  parser.add_argument('--sentinels', type=str)
  parser.add_argument('--redis-host', type=str, default='localhost')
  parser.add_argument('--no-uvloop', action='store_true')
  parser.add_argument('--host', type=str, default='localhost')
  parser.add_argument('--port', type=int, default=8080)
  args = parser.parse_args()

  app = web.Application()
  app[REDIS] = {
    SENTINEL: args.redis_use_sentinel,
    SENTINELS: args.sentinels,
    HOST: args.redis_host
  }
  app.on_startup.append(initialize_client_session)
  app.on_startup.append(initialize_keystore)
  app.on_cleanup.append(close_keystore)
  app.on_cleanup.append(close_client_session_connection)
  app.router.add_routes(routes)
  if not args.no_uvloop:
    asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
  web.run_app(app, host=args.host, port=args.port) 
Example #12
Source File: __init__.py    From schemathesis with MIT License 6 votes vote down vote up
def run_app(port: int, endpoints: List[Endpoint], spec: str, framework: str) -> None:
    if spec == "graphql":
        app = _graphql.create_app()
        app.run(port=port)
    else:
        if endpoints is not None:
            prepared_endpoints = tuple(endpoint.name for endpoint in endpoints)
        else:
            prepared_endpoints = tuple(endpoint.name for endpoint in Endpoint)
        version = {"openapi2": OpenAPIVersion("2.0"), "openapi3": OpenAPIVersion("3.0"),}[spec]
        if framework == "aiohttp":
            app = _aiohttp.create_openapi_app(prepared_endpoints, version)
            web.run_app(app, port=port)
        elif framework == "flask":
            app = _flask.create_openapi_app(prepared_endpoints, version)
            app.run(port=port) 
Example #13
Source File: __init__.py    From axibot with GNU General Public License v2.0 5 votes vote down vote up
def serve(opts):
    if opts.mock:
        bot = MockEiBotBoard()
    else:
        bot = EiBotBoard.find()

    try:
        app = make_app(bot)
        web.run_app(app, port=opts.port)
    finally:
        bot.close() 
Example #14
Source File: server.py    From gd.py with MIT License 5 votes vote down vote up
def run(app: web.Application, **kwargs) -> None:
    web.run_app(app, **kwargs) 
Example #15
Source File: app.py    From csgo_dont_blind_me with GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        self.update_brightness(force=True)

        self.app = web.Application()
        self.app.router.add_get('/', self.handle)
        self.app.router.add_post('/', self.handle)

        web.run_app(self.app, host=self.host, port=self.port) 
Example #16
Source File: main.py    From trace-examples with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main(argv):
    # init logging
    logging.basicConfig(level=logging.DEBUG)

    loop = asyncio.get_event_loop()

    app = init(loop, argv)
    web.run_app(app,
                host=app['config']['host'],
                port=app['config']['port']) 
Example #17
Source File: proxy_entrance.py    From proxy_tower with MIT License 5 votes vote down vote up
def run_server():
    app = proxy_server.ProxyServer(conf)
    web.run_app(app, port=conf.port) 
Example #18
Source File: webserver.py    From cocrawler with Apache License 2.0 5 votes vote down vote up
def make_app():
    loop = asyncio.get_event_loop()
    # TODO switch this to socket.getaddrinfo() -- see https://docs.python.org/3/library/socket.html
    serverip = config.read('REST', 'ServerIP')
    if serverip is None:
        return None
    serverport = config.read('REST', 'ServerPort')

    increment = False
    if isinstance(serverport, str) and serverport.endswith('+'):
        increment = True
        serverport = serverport[:-1]

    app = web.Application()
    app.router.add_get('/', frontpage)
    app.router.add_get('/api/{name}', api)

    # aiohttp 3.0 has AppRunner(). maybe I should switch to it?
    # also web.run_app(app, access_log=None) to turn off logging

    handler = app.make_handler()

    while True:
        try:
            f = loop.create_server(handler, serverip, serverport)
            break
        except OSError as e:  # address already in use
            if increment:
                LOGGER.info('OSError starting webserver: %s', repr(e))
                serverport += 1
                LOGGER.info('incrementing port to %d', serverport)
            else:
                raise

    srv = loop.run_until_complete(f)
    LOGGER.info('REST serving on %s', srv.sockets[0].getsockname())

    app['cocrawler'] = handler, srv
    return app 
Example #19
Source File: main.py    From education-sawtooth-simple-supply with Apache License 2.0 5 votes vote down vote up
def start_rest_api(host, port, messenger, database):
    loop = asyncio.get_event_loop()
    asyncio.ensure_future(database.connect())

    app = web.Application(loop=loop)
    # WARNING: UNSAFE KEY STORAGE
    # In a production application these keys should be passed in more securely
    app['aes_key'] = 'ffffffffffffffffffffffffffffffff'
    app['secret_key'] = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'

    messenger.open_validator_connection()

    handler = RouteHandler(loop, messenger, database)

    app.router.add_post('/authentication', handler.authenticate)

    app.router.add_post('/agents', handler.create_agent)
    app.router.add_get('/agents', handler.list_agents)
    app.router.add_get('/agents/{agent_id}', handler.fetch_agent)

    app.router.add_post('/records', handler.create_record)
    app.router.add_get('/records', handler.list_records)
    app.router.add_get('/records/{record_id}', handler.fetch_record)
    app.router.add_post(
        '/records/{record_id}/transfer', handler.transfer_record)
    app.router.add_post('/records/{record_id}/update', handler.update_record)

    LOGGER.info('Starting Simple Supply 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') 
Example #20
Source File: __main__.py    From video-funnel with MIT License 5 votes vote down vote up
def main():
    args = make_args()
    print(f'* Listening at port {args.port} ...')
    web.run_app(make_app(args), print=None, port=args.port) 
Example #21
Source File: proxy_provider_server.py    From proxy_py with GNU General Public License v3.0 5 votes vote down vote up
def start(self, loop):
        loop.run_until_complete(self.init())

        return web.run_app(self._app, host=self.host, port=self.port, loop=loop) 
Example #22
Source File: server.py    From tanner with GNU General Public License v3.0 5 votes vote down vote up
def start(self):
        loop = asyncio.get_event_loop()
        self.redis_client = loop.run_until_complete(redis_client.RedisClient.get_redis_client(poolsize=20))
        self.api = api.Api(self.redis_client)
        app = self.create_app(loop)
        host = TannerConfig.get('WEB', 'host')
        port = int(TannerConfig.get('WEB', 'port'))
        web.run_app(app, host=host, port=port) 
Example #23
Source File: server.py    From tanner with GNU General Public License v3.0 5 votes vote down vote up
def start(self):
        loop = asyncio.get_event_loop()
        self.redis_client = loop.run_until_complete(redis_client.RedisClient.get_redis_client(poolsize=20))
        self.api = api.Api(self.redis_client)
        set_auth = TannerConfig.get('API', 'auth')
        app = self.create_app(loop, set_auth)
        host = TannerConfig.get('API', 'host')
        port = int(TannerConfig.get('API', 'port'))

        if set_auth:
            key = generate()
            print('API_KEY for full access:', key)

        web.run_app(app, host=host, port=port) 
Example #24
Source File: server.py    From aiocache with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run_server(backend, loop=None):
    if loop:
        asyncio.set_event_loop(loop)
    app = web.Application()
    app["cache"] = CacheManager(backend)
    app.router.add_route("GET", "/", handler_get)
    web.run_app(app) 
Example #25
Source File: server.py    From tanner with GNU General Public License v3.0 5 votes vote down vote up
def start(self):
        loop = asyncio.get_event_loop()
        self.redis_client = loop.run_until_complete(redis_client.RedisClient.get_redis_client())

        app = self.create_app(loop)
        app.on_startup.append(self.start_background_delete)
        app.on_cleanup.append(self.cleanup_background_tasks)

        host = TannerConfig.get('TANNER', 'host')
        port = TannerConfig.get('TANNER', 'port')
        web.run_app(app, host=host, port=int(port)) 
Example #26
Source File: app.py    From cookiecutter-aiohttp-sqlalchemy with MIT License 5 votes vote down vote up
def run_app():
    """
    Application runner function.
    """
    ###
    # Create the application and read the host and port addresses
    #
    app = create_app()
    host = server_option("host")
    port = int(server_option("port"))

    ###
    # Access Log Format (Will not work with the dev server(for now))
    #
    # %a: Remote IP-address
    # %r: First line of request
    # %s: Response status code
    # %b: Size of response in bytes, excluding HTTP headers
    # %Tf: The time taken to serve the request, in seconds with fraction in %.06f format
    #
    access_log_format = '%a "%r" %s %b %Tf "%{Referrer}i" "%{User-Agent}i"'

    ###
    # Run the app using Aiohttp's web server
    #
    web.run_app(
        app=app, host=host, port=port, access_log=_logger,
        access_log_format=access_log_format) 
Example #27
Source File: preprocessors.py    From aries-staticagent-python with Apache License 2.0 5 votes vote down vote up
def main():
    """Create StaticConnection and start web server."""
    args = config()
    conn = StaticConnection(
        (args.my_verkey, args.my_sigkey),
        their_vk=args.their_verkey,
        endpoint=args.endpoint,
    )

    @conn.route(TYPE)
    @utils.validate(validate_basic_message)
    async def basic_message(msg, conn):
        """Respond to a basic message."""
        await conn.send_async({
            "@type": "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/"
                     "basicmessage/1.0/message",
            "~l10n": {"locale": "en"},
            "sent_time": utils.timestamp(),
            "content": (
                "The preprocessor validated this message and added: "
                "{}".format(msg['added_something'])
            )
        })

    async def handle(request):
        """aiohttp handle POST."""
        response = []
        with conn.session(response.append) as session:
            await conn.handle(await request.read(), session)

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

        raise web.HTTPAccepted()

    app = web.Application()
    app.add_routes([web.post('/', handle)])

    web.run_app(app, port=args.port) 
Example #28
Source File: return_route_server.py    From aries-staticagent-python with Apache License 2.0 5 votes vote down vote up
def main():
    """Start a server with a static connection."""
    keys = crypto.create_keypair(
        seed=hashlib.sha256(b'server').digest()
    )
    their_vk, _ = crypto.create_keypair(
        seed=hashlib.sha256(b'client').digest()
    )
    conn = StaticConnection(keys, their_vk=their_vk, endpoint=None)

    @conn.route('did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/basicmessage/1.0/message')
    async def basic_message_auto_responder(msg, conn):
        await conn.send_async({
            "@type": "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/"
                     "basicmessage/1.0/message",
            "~l10n": {"locale": "en"},
            "sent_time": utils.timestamp(),
            "content": "You said: {}".format(msg['content'])
        })

    async def handle(request):
        """aiohttp handle POST."""
        response = []
        with conn.session(response.append) as session:
            await conn.handle(await request.read(), session)

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

        raise web.HTTPAccepted()

    app = web.Application()
    app.add_routes([web.post('/', handle)])

    web.run_app(app, port=os.environ.get('PORT', 3000)) 
Example #29
Source File: webserver_aiohttp.py    From aries-staticagent-python with Apache License 2.0 5 votes vote down vote up
def main():
    """Create StaticConnection and start web server."""
    args = config()
    conn = StaticConnection(
        (args.my_verkey, args.my_sigkey),
        their_vk=args.their_verkey,
        endpoint=args.endpoint,
    )

    @conn.route("did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/basicmessage/1.0/message")
    async def basic_message(msg, conn):
        """Respond to a basic message."""
        await conn.send_async({
            "@type": "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/"
                     "basicmessage/1.0/message",
            "~l10n": {"locale": "en"},
            "sent_time": utils.timestamp(),
            "content": "You said: {}".format(msg['content'])
        })

    async def handle(request):
        """aiohttp handle POST."""
        response = []
        with conn.session(response.append) as session:
            await conn.handle(await request.read(), session)

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

        raise web.HTTPAccepted()

    app = web.Application()
    app.add_routes([web.post('/', handle)])

    web.run_app(app, port=args.port) 
Example #30
Source File: __init__.py    From black with MIT License 5 votes vote down vote up
def main(bind_host: str, bind_port: int) -> None:
    logging.basicConfig(level=logging.INFO)
    app = make_app()
    ver = black.__version__
    black.out(f"blackd version {ver} listening on {bind_host} port {bind_port}")
    web.run_app(app, host=bind_host, port=bind_port, handle_signals=True, print=None)