Exemple #1
0
def main():
    loop = asyncio.get_event_loop()
    app = web.Application(loop=loop)
    app.router.add_route('GET', '/slow', slow_handler)
    app.router.add_route('GET', '/fast', fast_handler)

    web.run_app(app, port=8888)
Exemple #2
0
def main():
    """
        Main method for the Talos webserver. Sets up and runs the webserver
    :return: Exit code
    """
    settings = load_settings()

    if settings["tokens"].get("ssl_cert"):
        sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        cert = pathlib.Path(__file__).parent / settings["tokens"]["ssl_cert"]
        key = pathlib.Path(__file__).parent / settings["tokens"]["ssl_key"]
        sslcontext.load_cert_chain(cert, key)
    else:
        sslcontext = None

    app = TalosApplication()
    app.apply_settings(settings)

    site_handler = handlers.SiteHandler(app=app)
    auth_handler = handlers.AuthHandler(app=app)
    api_handler = handlers.APIHandler(app=app)

    app.add_routes([
        web.get("/{tail:(?!api/|auth/).*}", site_handler.get),
        web.head("/{tail:(?!api/|auth/).*}", site_handler.head),
        web.get("/api/{tail:.*}", api_handler.get),
        web.post("/api/{tail:.*}", api_handler.post),
        web.get("/auth/{tail:.*}", auth_handler.get)
    ])
    web.run_app(app, port=443 if sslcontext else 80, ssl_context=sslcontext)
    return 0
def main():
    app_eui = os.environ.get('TTN_APP_EUI')
    access_key = os.environ.get('TTN_ACCESS_KEY')
    ttn_host = os.environ.get('TTN_HOST', 'staging.thethingsnetwork.org')
    ca_cert_path = os.environ.get('TTN_CA_CERT_PATH', 'mqtt-ca.pem')

    args = parser.parse_args()
    logging.basicConfig(level=args.loglevel)

    # Setup the MQTT client
    client = get_mqtt_client(
        app_eui=app_eui,
        access_key=access_key,
        host=ttn_host,
        ca_cert_path=ca_cert_path
    )

    # Configure the web application
    app = web.Application()
    app.router.add_route(
        'GET', '/', home,
    )
    app.router.add_route(
        'GET', '/data/', websocket,
    )
    app.router.add_static(
        '/static/',
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'html'),
    )

    # Start the periodical MQTT update and the web app
    asyncio.async(check_mqtt(client))
    web.run_app(app, port=args.port, host=args.host)
Exemple #4
0
def server():
    """ Main server """
    app = web.Application()
    app.router.add_route('*', '/get/{series}/{season}/{chapter}', PyChapterAPI)
    app.router.add_route('*', '/get/{magnet}', PyChapterAPI)
    app.router.add_static("/streams/", pathlib.Path('.').absolute())
    web.run_app(app)
Exemple #5
0
 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)
     host = TannerConfig.get('TANNER', 'host')
     port = TannerConfig.get('TANNER', 'port')
     web.run_app(app, host=host, port=int(port))
Exemple #6
0
def test_run_app_context_vars(patched_loop):
    from contextvars import ContextVar

    count = 0
    VAR = ContextVar('VAR', default='default')

    async def on_startup(app):
        nonlocal count
        assert 'init' == VAR.get()
        VAR.set('on_startup')
        count += 1

    async def on_cleanup(app):
        nonlocal count
        assert 'on_startup' == VAR.get()
        count += 1

    async def init():
        nonlocal count
        assert 'default' == VAR.get()
        VAR.set('init')
        app = web.Application()

        app.on_startup.append(on_startup)
        app.on_cleanup.append(on_cleanup)
        count += 1
        return app

    web.run_app(init(), print=stopper(patched_loop))
    assert count == 3
Exemple #7
0
def test_run_app_multiple_preexisting_sockets(loop, mocker):
    skip_if_no_dict(loop)

    mocker.spy(loop, 'create_server')

    app = web.Application()
    mocker.spy(app, 'startup')

    sock1 = socket.socket()
    sock2 = socket.socket()
    with contextlib.closing(sock1), contextlib.closing(sock2):
        sock1.bind(('0.0.0.0', 0))
        _, port1 = sock1.getsockname()
        sock2.bind(('0.0.0.0', 0))
        _, port2 = sock2.getsockname()

        printer = mock.Mock(wraps=stopper(loop))
        web.run_app(app, loop=loop, sock=(sock1, sock2), print=printer)

        loop.create_server.assert_has_calls([
            mock.call(mock.ANY, sock=sock1, backlog=128, ssl=None),
            mock.call(mock.ANY, sock=sock2, backlog=128, ssl=None)
        ])
        app.startup.assert_called_once_with()
        assert "http://0.0.0.0:{}".format(port1) in printer.call_args[0][0]
        assert "http://0.0.0.0:{}".format(port2) in printer.call_args[0][0]
Exemple #8
0
def test_run_app_cancels_failed_tasks(patched_loop):
    app = web.Application()
    task = None

    exc = RuntimeError("FAIL")

    async def fail():
        try:
            await asyncio.sleep(1000)
        except asyncio.CancelledError:
            raise exc

    async def on_startup(app):
        nonlocal task
        loop = asyncio.get_event_loop()
        task = loop.create_task(fail())
        await asyncio.sleep(0.01)

    app.on_startup.append(on_startup)

    exc_handler = mock.Mock()
    patched_loop.set_exception_handler(exc_handler)
    web.run_app(app, print=stopper(patched_loop))
    assert task.done()

    msg = {
        'message': 'unhandled exception during asyncio.run() shutdown',
        'exception': exc,
        'task': task,
    }
    exc_handler.assert_called_with(patched_loop, msg)
Exemple #9
0
def test_run_app_multiple_preexisting_sockets(loop, mocker):
    mocker.spy(loop, 'create_server')
    loop.call_later(0.05, loop.stop)

    app = web.Application()
    mocker.spy(app, 'startup')

    sock1 = socket.socket()
    sock2 = socket.socket()
    with contextlib.closing(sock1), contextlib.closing(sock2):
        sock1.bind(('0.0.0.0', 0))
        _, port1 = sock1.getsockname()
        sock2.bind(('0.0.0.0', 0))
        _, port2 = sock2.getsockname()

        printed = StringIO()
        web.run_app(app, loop=loop, sock=(sock1, sock2), print=printed.write)

        assert loop.is_closed()
        loop.create_server.assert_has_calls([
            mock.call(mock.ANY, sock=sock1, backlog=128, ssl=None),
            mock.call(mock.ANY, sock=sock2, backlog=128, ssl=None)
        ])
        app.startup.assert_called_once_with()
        assert "http://0.0.0.0:{}".format(port1) in printed.getvalue()
        assert "http://0.0.0.0:{}".format(port2) in printed.getvalue()
Exemple #10
0
def main():
    config.parse_args(sys.argv[1:])

    setup_logging()
    print_config()
    create_missing_dirs()

    storage = build_storage()
    storage.open()

    app = create_app(storage, config['sync.url'])

    if config['debug'] and aioreloader:
        aioreloader.start(hook=storage.close)

    try:
        socket_path = config['api.socket']
        logger.info('Starting server on socket {}'.format(socket_path))
        web.run_app(app, path=socket_path)
    except Exception as e:
        logger.error('Backend error: {}'.format(e))
        raise
    finally:
        storage.close()
        logger.info('nete-backend ended.')
Exemple #11
0
def server():
    """
        Starts main dispatch server
    """
    allowed_domains = []

    opts = docopt(__doc__, version="0.0.1")

    logging.basicConfig(level=getattr(logging, opts.pop('loglevel')))
    r.set_loop_type("asyncio")

    with suppress(KeyError):
        allowed_domains = opts.pop('allowed_domains').split(',')
        allowed_domains = [a.strip() for a in allowed_domains]

    app = web.Application()
    app['rethinkdb'] = opts

    default_opts = aiohttp_cors.ResourceOptions(
        allow_credentials=True, expose_headers="*", allow_headers="*")
    cors = aiohttp_cors.setup(app, defaults={
        dom: default_opts for dom in allowed_domains})

    cors.add(cors.add(app.router.add_resource('/')).add_route('*', Dispatcher))
    cors.add(cors.add(app.router.add_resource('/ws')).add_route('*', wshandle))
    web.run_app(app)
Exemple #12
0
def main(args=sys.argv[1:]):
    # write access/error logs to stderr
    logging.basicConfig()
    logging.getLogger('aiohttp').setLevel(logging.INFO)

    conf = get_conf()
    database = create_connection(conf)

    # The secret is required to sign issued JWT tokens, therefore it's crucial
    # to warn about importance of settings secret before going production. The
    # only reason why we don't enforce it's setting is because we want the app
    # to fly (at least for development purpose) using defaults.
    if not conf.get('AUTH_SECRET', ''):
        warnings.warn(
            'Auth secret has not been provided. Please generate a long random '
            'secret before going to production.')
        conf['AUTH_SECRET'] = binascii.hexlify(os.urandom(32)).decode('ascii')

    with picobox.push(picobox.Box()) as box:
        box.put('conf', conf)
        box.put('database', database)

        web.run_app(
            create_app(conf, database),
            host=conf['SERVER_HOST'],
            port=conf['SERVER_PORT'],
            access_log_format=conf['SERVER_ACCESS_LOG_FORMAT'],
        )
Exemple #13
0
def test_run_app_custom_backlog(patched_loop):
    app = web.Application()
    web.run_app(app, backlog=10, print=stopper(patched_loop))

    patched_loop.create_server.assert_called_with(
        mock.ANY, '0.0.0.0', 8080, ssl=None, backlog=10,
        reuse_address=None, reuse_port=None)
Exemple #14
0
def run(cmdargs=None, logprefix=''):
    if cmdargs:
        config.args = config.parser.parse_args(args=cmdargs)
    else:
        config.args = config.parser.parse_args()

    logging.basicConfig(
        format=logprefix + '{asctime} {levelname} {name}: {message}',
        style='{',
        level=logging.DEBUG if config.args.verbose else logging.WARNING
    )

    if not os.path.exists(config.args.queue):
        os.makedirs(config.args.queue)
    replication.dellog = DeletionLog(os.path.join(config.args.queue, 'deletion.log'))

    logger.info('Starting up...')
    loop = asyncio.get_event_loop()
    start_replication_workers(loop)
    app = create_app(loop)
    app.on_response_prepare.append(on_response_prepare)
    web.run_app(app, port=config.args.port, host=config.args.host, print=logger.info)
    logger.info('Starting to tear down workers...')
    stop_replication_workers(loop)
    logger.info('Goodbye.')
Exemple #15
0
def main():
    # init logging
    logging.basicConfig(level=logging.DEBUG)

    loop = asyncio.get_event_loop()
    app = loop.run_until_complete(init(loop))
    web.run_app(app)
Exemple #16
0
def server():
    app = web.Application()
    app['status'] = Status().load()
    app.router.add_route('*', '/api/{what}', StatusAPI)
    app.router.add_route('*', '/api', StatusAPI)
    app.on_shutdown.append(on_shutdown)
    web.run_app(app)
Exemple #17
0
def test_run_app_abstract_linux_socket(loop, mocker):
    sock_path = b"\x00" + uuid4().hex.encode('ascii')

    loop.call_later(0.05, loop.stop)
    app = web.Application(loop=loop)
    web.run_app(
        app, path=sock_path.decode('ascii', 'ignore'),
        print=lambda *args: None)
    assert loop.is_closed()

    # New app run using same socket path
    with loop_context() as loop:
        mocker.spy(loop, 'create_unix_server')
        loop.call_later(0.05, loop.stop)

        app = web.Application(loop=loop)

        mocker.spy(app, 'startup')
        mocker.spy(os, 'remove')
        printed = StringIO()

        web.run_app(app, path=sock_path, print=printed.write)

        # Abstract paths don't exist on the file system, so no attempt should
        # be made to remove.
        assert mock.call([sock_path]) not in os.remove.mock_calls

        loop.create_unix_server.assert_called_with(
            mock.ANY,
            sock_path,
            ssl=None,
            backlog=128
        )
        app.startup.assert_called_once_with()
Exemple #18
0
    def run(self, port=None, server=None, debug=None, host=None, **options):
        if port is not None:
            self.port = port
        elif self.port is None:
            self.port = 5000

        self.server = server or self.server
        self.host = host or self.host or '0.0.0.0'

        if debug is not None:
            self.debug = debug
            self.app._debug = debug
            for subapp in self.app._subapps:
                subapp._debug = debug

        logger.debug('Starting %s HTTP server..', self.server, extra=vars(self))

        if self.server == 'aiohttp':
            logger.info('Listening on %s:%s..', self.host, self.port)

            access_log = options.get('access_log')

            if options.get('use_default_access_log'):
                access_log = logger

            web.run_app(self.app, port=self.port, host=self.host, access_log=access_log)
        else:
            raise Exception('Server {} not recognized'.format(self.server))
Exemple #19
0
def runserver(host, port, amqp_uri):
    app = web.Application()
    app['RPC_CONFIG'] = {
        'AMQP_URI': amqp_uri
    }
    app.router.add_route('POST', '/trigger_digest', trigger_digest)
    web.run_app(app, host=host, port=port)
Exemple #20
0
def main(**kwargs):
    parser = argparse.ArgumentParser()
    parser.add_argument('-p', '--port', type=int, help='server port',
                        default=kwargs.get('port', 8245))
    parser.add_argument('--host', help='server host',
                        default=kwargs.get('host', '0.0.0.0'))
    parser.add_argument('--no-pir', help='disable pir sensor',
                        action='store_true',
                        default=kwargs.get('no_pir', False))
    parser.add_argument('--lock', help='disable auto closing garage',
                        action='store_true',
                        default=kwargs.get('lock', False))
    parser.add_argument('--notify', help='push door change notifications',
                        action='store_true',
                        default=kwargs.get('no_notify', True))
    args = parser.parse_args()

    app['pi'].ignore_pir = args.no_pir
    app['garage'].lock(args.lock)
    app['notify'] = args.notify
    try:
        web.run_app(app, host=args.host, port=args.port)
    finally:
        app['pi'].stop()
        app['garage'].save(notify=app['notify'])
Exemple #21
0
def test_run_app_custom_backlog_unix(patched_loop):
    app = web.Application()
    web.run_app(app, path='/tmp/tmpsock.sock',
                backlog=10, print=stopper(patched_loop))

    patched_loop.create_unix_server.assert_called_with(
        mock.ANY, '/tmp/tmpsock.sock', ssl=None, backlog=10)
def run_webserver(port=8080):
    app = web.Application()
    aiohttp_jinja2.setup(app, loader=FSLoader(os.curdir, followlinks=True))
    app.router.add_route('GET', '/', handler)
    # Thanks, @asvetlov -- app.router.add_static() was the key!
    # https://github.com/aio-libs/aiohttp_jinja2/issues/26
    app.router.add_static('/static/', path='./static', name='static')
    web.run_app(app, port=port)
Exemple #23
0
 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('API', 'host')
     port = int(TannerConfig.get('API', 'port'))
     web.run_app(app, host=host, port=port)
Exemple #24
0
def init():
    app = web.Application()
    app.get = lambda path: (lambda fn: app.router.add_route('GET', path, fn))

    app.router.add_resource(r'/api/parse_match_amr').add_route('POST', parse_match_amr)
    app.router.add_resource(r'/api/test_data').add_route('GET', parse_test)
    app.router.add_resource(r'/{path:.*}').add_route('GET', static_file)
    web.run_app(app, host=args.host, port=args.port)
Exemple #25
0
def main():
    # init logging
    logging.basicConfig(level=logging.DEBUG)

    app = init()
    web.run_app(app,
                host=app['config']['host'],
                port=app['config']['port'])
def main():
    app = web.Application()
    app['theodore'] = TheodoreServer()
    app.router.add_route('GET', '/ws', get_multichannel_websocket)
    app.router.add_route('GET', '/{name}', get)
    app.router.add_route('POST', '/{name}', post)
    app.router.add_route('GET', '/', get_multichannel)
    web.run_app(app, port=7300)
Exemple #27
0
def test_run_app_close_loop(patched_loop) -> None:
    app = web.Application()
    web.run_app(app, print=stopper(patched_loop))

    patched_loop.create_server.assert_called_with(mock.ANY, '0.0.0.0', 8080,
                                                  ssl=None, backlog=128,
                                                  reuse_address=None,
                                                  reuse_port=None)
    assert patched_loop.is_closed()
def run_bot(bot_cls, host='localhost', port=None):
    app = web.Application()
    
    with bot_cls() as my_bot:
        app.router.add_route('POST', '/api', my_bot._handler)
        if __debug__:
            app.router.add_route('GET', '/history', my_bot._history)

        web.run_app(app, host, int(port))
Exemple #29
0
def test_run_app_mixed_bindings(mocker, run_app_kwargs, expected_server_calls,
                                expected_unix_server_calls):
    app = mocker.MagicMock()
    mocker.patch('asyncio.gather')

    web.run_app(app, print=lambda *args: None, **run_app_kwargs)

    assert app.loop.create_unix_server.mock_calls == expected_unix_server_calls
    assert app.loop.create_server.mock_calls == expected_server_calls
Exemple #30
0
def test_run_app_https(patched_loop):
    app = web.Application()

    ssl_context = ssl.create_default_context()
    web.run_app(app, ssl_context=ssl_context, print=stopper(patched_loop))

    patched_loop.create_server.assert_called_with(
        mock.ANY, '0.0.0.0', 8443, ssl=ssl_context, backlog=128,
        reuse_address=None, reuse_port=None)