コード例 #1
0
ファイル: example.py プロジェクト: basurlakh/torrentstream
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)
コード例 #2
0
ファイル: dispatcher.py プロジェクト: XayOn/tqueues
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)
コード例 #3
0
ファイル: server.py プロジェクト: afeena/tanner
 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))
コード例 #4
0
ファイル: app.py プロジェクト: bj0/pirage
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'])
コード例 #5
0
ファイル: __main__.py プロジェクト: xsnippet/xsnippet-api
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'],
        )
コード例 #6
0
ファイル: aiohttp_app.py プロジェクト: crunk1/connexion
    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))
コード例 #7
0
ファイル: test_run_app.py プロジェクト: singulared/aiohttp
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()
コード例 #8
0
ファイル: server.py プロジェクト: raphaelm/cockatiel
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.')
コード例 #9
0
ファイル: __init__.py プロジェクト: biazzotto/HackerspacePI
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)
コード例 #10
0
ファイル: test_run_app.py プロジェクト: 3lnc/aiohttp
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)
コード例 #11
0
ファイル: test_run_app.py プロジェクト: 3lnc/aiohttp
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)
コード例 #12
0
ファイル: main.py プロジェクト: argaen/aiohttp
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)
コード例 #13
0
ファイル: api.py プロジェクト: andriykohut/reddgester
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)
コード例 #14
0
ファイル: demo.py プロジェクト: skolsuper/thaipy
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)
コード例 #15
0
ファイル: test_run_app.py プロジェクト: grehujt/aiohttp
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]
コード例 #16
0
ファイル: talos_server.py プロジェクト: CraftSpider/TalosBot
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
コード例 #17
0
ファイル: main.py プロジェクト: fqxp/nete
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.')
コード例 #18
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)
コード例 #19
0
ファイル: test_run_app.py プロジェクト: gleb-chipiga/aiohttp
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()
コード例 #20
0
ファイル: test_run_app.py プロジェクト: KeepSafe/aiohttp
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
コード例 #21
0
ファイル: test_run_app.py プロジェクト: KeepSafe/aiohttp
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)
コード例 #22
0
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)
コード例 #23
0
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)
コード例 #24
0
ファイル: main.py プロジェクト: cr0hn/aiohttp
def main():
    # init logging
    logging.basicConfig(level=logging.DEBUG)

    app = init()
    web.run_app(app,
                host=app['config']['host'],
                port=app['config']['port'])
コード例 #25
0
ファイル: server.py プロジェクト: didzis/smatchTools
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)
コード例 #26
0
ファイル: server.py プロジェクト: afeena/tanner
 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)
コード例 #27
0
ファイル: test_run_app.py プロジェクト: 3lnc/aiohttp
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)
コード例 #28
0
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))
コード例 #29
0
ファイル: test_run_app.py プロジェクト: KazuCocoa/aiohttp
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()
コード例 #30
0
ファイル: test_run_app.py プロジェクト: singulared/aiohttp
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
コード例 #31
0
 def run(self):
     web.run_app(self.app, **self.config['app'])
コード例 #32
0
ファイル: gateway_stub.py プロジェクト: zeroday0619/hikari
    async def receive_identify(self):
        payload = await self.poll_messages()
        if payload["op"] != 2:
            print("Expected IDENTIFY, got", payload)
            await self.ws.close(code=4003, message=b"not authenticated")
        else:
            print("received IDENTIFY", payload)

    async def poll_messages(self):
        while True:
            payload = await self.ws.receive_json()
            op = payload["op"]

            if op == 1:
                print("Recv heartbeat, seq =", payload["d"])
                self.last_heartbeat = time.perf_counter()
                print("Sending heartbeat ack")
                await self.ws.send_json({"op": 11, "d": None})
                continue

            if op == 11:
                print("Recv Heartbeat ACK")
                continue

            return payload


server = web.Application()
server.add_routes(route_table)
web.run_app(server, host=host, port=port)
コード例 #33
0
ファイル: app.py プロジェクト: fero-l/python3-webapp
def init():
    app=web.Application()
    app.router.add_get('/',index)
    web.run_app(app,host='127.0.0.1',port=9000)
コード例 #34
0
from aiohttp import web
from api.routes import vehicle_router


async def init_app() -> web.Application:
    app = web.Application()
    app.add_routes(vehicle_router)
    return app


web.run_app(init_app())
コード例 #35
0
@aiohttp_tal.template('valid.html')
async def page(request):
    return {
        'title': 'Valid W3C page',
        'intro': "Validated on https://validator.w3.org",
    }


async def create_app():
    app = web.Application()
    app.update(name='Testing aiohttp TAL')

    tal_loader = PageTemplateLoader(
        str(THIS_DIR / 'templates'),
        enable_data_attributes=True,  # data-tal-*
        auto_reload=True  # debugging
    )
    aiohttp_tal.setup(app, loader=tal_loader)

    app.add_routes([web.static('/static', str(THIS_DIR / 'static'))])
    app['static_root_url'] = '/static'
    app.router.add_get('/', index, name='index')
    app.router.add_get('/page', page, name='translation')

    return app


if __name__ == '__main__':
    web.run_app(create_app(), host='127.0.0.1', port=8080)
コード例 #36
0
ファイル: main.py プロジェクト: pirat898/demo_lecture_3
def init_rmq():
    with pika.BlockingConnection(pika.URLParameters(RMQ_URL)) as connection:
        with connection.channel() as channel:
            channel.exchange_declare(exchange='to_direct',
                                     exchange_type="fanout",
                                     durable=True)


if __name__ == '__main__':
    app = web.Application()

    app.add_routes([
        web.get('/', home_view, name='home'),
        web.get('/get_sync_data/', get_sync_data, name='get_sync_data'),
        web.get('/get_sync_long_data/',
                get_sync_long_data,
                name='get_sync_long_data'),
        web.post('/send_rmq_direct/', send_rmq_direct, name='send_rmq_direct'),
        web.post('/update_task_status_api/',
                 update_task_status_api,
                 name='update_task_status_api'),
    ])

    aiohttp_jinja2.setup(app,
                         loader=jinja2.FileSystemLoader('./api/templates'))

    init_rmq()

    web.run_app(app, host='0.0.0.0')
コード例 #37
0
import http

ROOM = 'room'

sio = socketio.AsyncServer(cors_allowed_origins='*')
app = web.Application()
sio.attach(app)


@sio.event
async def connect(sid, environ):
    print('Connected', sid)
    await sio.emit('ready', room=ROOM, skip_sid=sid)
    sio.enter_room(sid, ROOM)


@sio.event
def disconnect(sid):
    sio.leave_room(sid, ROOM)
    print('Disconnected', sid)


@sio.event
async def data(sid, data):
    print('Message from {}: {}'.format(sid, data))
    await sio.emit('data', data, room=ROOM, skip_sid=sid)


if __name__ == '__main__':
    web.run_app(app, port=9999)
コード例 #38
0
ファイル: main.py プロジェクト: arianamiri/aiohttpapp
from aiohttp import web

from concierge.routes import setup_routes

app = web.Application()
setup_routes(app)

if __name__ == '__main__':
    web.run_app(app, port=5858)
コード例 #39
0
ファイル: service_c.py プロジェクト: yunstanford/aiozipkin
host = '127.0.0.1'
port = 9002


async def handler(request):
    await asyncio.sleep(0.01)
    payload = {
        'name': 'servcie_c',
        'host': host,
        'port': port,
        'children': [],
    }
    return web.json_response(payload)


async def make_app():
    app = web.Application()
    app.router.add_get('/api/v1/data', handler)

    zipkin_address = 'http://127.0.0.1:9411'
    endpoint = az.create_endpoint('service_c', ipv4=host, port=port)
    tracer = az.create(zipkin_address, endpoint, sample_rate=1.0)
    az.setup(app, tracer)
    return app


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    app = loop.run_until_complete(make_app())
    web.run_app(app, host=host, port=port)
コード例 #40
0
ファイル: app.py プロジェクト: JoseCarlosRoLo14/Completo
# Create the Bot
BOT = WelcomeUserBot(USER_STATE)


# Listen for incoming requests on /api/messages.
async def messages(req: Request) -> Response:
    # Main bot message handler.
    if "application/json" in req.headers["Content-Type"]:
        body = await req.json()
    else:
        return Response(status=415)

    activity = Activity().deserialize(body)
    auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""

    response = await ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
    if response:
        return json_response(data=response.body, status=response.status)
    return Response(status=201)


APP = web.Application(middlewares=[aiohttp_error_middleware])
APP.router.add_post("/api/messages", messages)

if __name__ == "__main__":
    try:
        web.run_app(APP, host="localhost", port=CONFIG.PORT)
    except Exception as error:
        raise error
コード例 #41
0
from aiohttp import web


async def index(request):
    return web.Response(text="hello Aiohttp!")


def setup_routes(app):
    app.router.add_get('/', index)


app = web.Application()
setup_routes(app)
web.run_app(app, host='127.0.0.1', port='8080')
コード例 #42
0
ファイル: app.py プロジェクト: tumb1er/aiodav
# coding: utf-8

import aiohttp_debugtoolbar
from aiohttp import web

from aiodav import resources
from aiodav.contrib import setup

app = web.Application()

aiohttp_debugtoolbar.setup(app)

setup(app, mounts={'TEST': resources.FileSystemResource('TEST')})

if __name__ == '__main__':
    web.run_app(app)
コード例 #43
0
        web.get('/results/{id}', get_result),
        web.get('/tasks/uuid/{uuid}', get_task_with_uuid),
        web.post('/tasks', create_task),
        web.post('/tasks/{id}/suspend', suspend_task),
        web.post('/tasks/{id}/resume', resume_task),
        web.post('/tasks/{id}/result', post_result),
        web.delete('/tasks/{id}', delete_task),
        web.delete('/results/{id}', delete_result)
    ])

    connect('steadyobserver', host=mongo_host, port=mongo_port)

    print("Building scheduler data stores")
    job_stores = {
        'default': MongoDBJobStore(host=mongo_host, port=mongo_port)
    }  # password=mongo_pass, username=mongo_user)}
    executors = {'default': ThreadPoolExecutor(20)}
    job_defaults = {'coalesce': False, 'max_instances': 3}

    scheduler = AsyncIOScheduler(jobstores=job_stores,
                                 executors=executors,
                                 job_defaults=job_defaults,
                                 timezone=utc)
    print("Starting scheduler")
    scheduler.start()
    scheduler.print_jobs()
    scheduler_lock = Lock()

    print("SteadyObserver listening...")
    web.run_app(app, host=listen_host, port=listen_port)
コード例 #44
0
ファイル: test_run_app.py プロジェクト: vuchau/aiohttp
        sock2.bind(('0.0.0.0', 0))
        _, port2 = sock2.getsockname()

        printer = mock.Mock(wraps=stopper(loop))
        web.run_app(app, 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]


_script_test_signal = """
from aiohttp import web

app = web.Application()
web.run_app(app, host=())
"""


def test_sigint(loop, mocker):
    skip_if_on_windows()

    proc = subprocess.Popen([sys.executable, "-u", "-c", _script_test_signal],
                            stdout=subprocess.PIPE)
    for line in proc.stdout:
        if line.startswith(b"======== Running on"):
            break
コード例 #45
0
ファイル: front.py プロジェクト: xavier-ruiz/tp2
        resp = f"""
        You called at : {json_data['time']} (dynamic)
        On environment : {json_data['environment']} (from env variable)
        With path : {json_data['result']}   (from URL path)
        With front : {os.uname()[1]} (from real hostname of front service)
        With back  : {json_data['hostname']} (from real hostname of back service)
        """
    
    return web.Response(text=resp)

async def write_to_file(request):
    something = request.match_info.get('something', "")

    print(something)
    if something:
        resp=something

        url=f"http://{os.environ['WS_BACK_URL']}:8080/write/{something}"
        response = requests.get(url)
    else:
        resp="There is nothing to print"

    return web.Response(text=resp)

app = web.Application()
app.add_routes([web.get('/', handle),
                web.get('/{name}', handle),
                web.get('/write/{something}', write_to_file)])

web.run_app(app, port=os.environ['APP_PORT'])
コード例 #46
0
@router.register("pull_request", action="opened")
async def pull_opened_event(event, gh, *args, **kwargs):
    url = event.data['pull_request']['issue_url']
    await gh.post(url, data={'labels': ["pending-review"]})


async def main(request):
    body = await request.read()

    secret = os.environ.get('GH_SECRET')
    oauth_token = os.environ.get("GH_AUTH")

    event = sansio.Event.from_http(request.headers, body, secret=secret)

    async with aiohttp.ClientSession() as session:
        gh = gh_aiohttp.GitHubAPI(session, "ndpete", oauth_token=oauth_token)

        # call appropriate  callback for the event
        await router.dispatch(event, gh)

    return web.Response(status=200)


if __name__ == "__main__":
    app = web.Application()
    app.router.add_post("/", main)
    port = os.environ.get("PORT")
    if port is not None:
        port = int(port)
    web.run_app(app, port=port)
コード例 #47
0
lastResults = RawArray(DETECT_RESULT, max_result_count)
for i in range(max_result_count):
    lastResults[i] = DETECT_RESULT(0, 0, 0, 0, 0)

# --- start web app ---
if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='WebRTC audio / video / data-channels demo')
    parser.add_argument('--port',
                        type=int,
                        default=8080,
                        help='Port for HTTP server (default: 8080)')
    parser.add_argument('--verbose', '-v', action='count')
    args = parser.parse_args()

    if args.verbose:
        logging.basicConfig(level=logging.DEBUG)

    # --- executor for worker process --
    # WARN; currentry for 1 PeerConnection
    #executor = ProcessPoolExecutor(1)
    executor = ThreadPoolExecutor(1)

    # --- web app --
    app = web.Application()
    app.on_shutdown.append(on_shutdown)
    app.router.add_get('/', index)
    app.router.add_get('/client.js', javascript)
    app.router.add_post('/offer', offer)
    web.run_app(app, port=args.port)
コード例 #48
0
async def init_app():
    from myapp.events_handler import event_routes
    from myapp.websocket import ws_routes

    wsgi_handler = WSGIHandler(application)
    app = web.Application()

    # routes
    app.router.add_routes(ws_routes)
    app.router.add_routes(event_routes)
    app.router.add_route("*", "/{path_info:.*}", wsgi_handler)

    # # pg
    # db_url = config('DATABASE_URL', default='', cast=parse)
    # app['pgpool'] = await asyncpg.create_pool(
    #     database=db_url['NAME'],
    #     user=db_url['USER'],
    #     password=db_url['PASSWORD'],
    #     host=db_url['HOST'],
    #     port=db_url['PORT']
    # )

    # # redis
    # app['redispool'] = await aioredis.create_redis_pool(settings.REDIS_URL, minsize=5, maxsize=10, loop=loop)

    return app


loop = asyncio.get_event_loop()
web.run_app(loop.run_until_complete(init_app()), port=8000)
コード例 #49
0
async def handle(request):
    name = request.match_info.get('name', "Anonymous")
    text = "Hello, " + name
    return web.Response(text=text)


async def wshandle(request):
    ws = web.WebSocketResponse()
    await ws.prepare(request)

    async for msg in ws:
        if msg.type == web.WSMsgType.text:
            await ws.send_str("Hello, {}".format(msg.data))
        elif msg.type == web.WSMsgType.binary:
            await ws.send_bytes(msg.data)
        elif msg.type == web.WSMsgType.close:
            break

    return ws


app = web.Application()
app.add_routes([
    web.get('/', handle),
    web.get('/echo', wshandle),
    web.get('/{name}', handle)
])

web.run_app(app, host="127.0.0.1", port=9090)
コード例 #50
0
import asyncio
import logging

from aiohttp import web
from aiohttp_apispec import setup_aiohttp_apispec

import settings
from integrations import INTEGRATIONS
from middleware import MIDDLEWARES
from routes import setup_routes


async def create_app() -> web.Application:
    """
    Инизиализирует приложение
    :return:
    """
    app = web.Application(middlewares=MIDDLEWARES)
    app.cleanup_ctx.extend(INTEGRATIONS)
    setup_routes(app)
    setup_aiohttp_apispec(app, **settings.APISPEC_CONF)
    return app


logging.basicConfig(level=logging.INFO if settings.DEBUG else logging.WARNING)

LOOP = asyncio.get_event_loop()

if __name__ == '__main__':
    web.run_app(create_app(), port=8118)
コード例 #51
0
    # When we receive a new event of type
    # 'message' through a socket.io connection
    # we print the socket ID and the message
    print("Socket ID: ", sid)
    print(message)
    await sio.emit('channel_b', message)


@sio.on('channel_c')
async def passData(sid, message):
    print("Socket ID: ", sid)
    print(message)
    await sio.emit('channel_c', message)


@sio.on('channel_d')
async def passData(sid, message):
    print("Socket ID: ", sid)
    print(message)
    await sio.emit('channel_d', message)


# We bind our aiohttp endpoint to our app
# router
app.router.add_get('/', index)
app.router.add_static('/static/', path='static', name='static')

# We kick off our server
if __name__ == '__main__':
    web.run_app(app, host='0.0.0.0', port=8888)
コード例 #52
0
ファイル: manage.py プロジェクト: Steinerr/wg_test
def runwriter():
    web.run_app(writer_app, host='0.0.0.0', port=8070)
コード例 #53
0
ファイル: server.py プロジェクト: jersobh/pydge
#!/usr/bin/env python
# encoding: utf-8
import sys
import os
import core.conf
import asyncio
import jinja2
import aiohttp_jinja2
from aiohttp import web
from core.router import routes
from core.conf import *

loop = asyncio.get_event_loop()
app = web.Application(loop=loop)
routes(app)
aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('views/templates'))
web.run_app(app, host='0.0.0.0', port=APP_PORT)
コード例 #54
0
ファイル: t3.py プロジェクト: thinkingjxj/Python
from aiohttp import web


async def indexhandle(request:web.Request):
    return web.Response(text=request.path, status=201)

async def handle(request:web.Request):
    print(request.match_info)
    print(request.query_string)   # http://127.0.0.1:8080/1?name=12301
    return web.Response(text=request.match_info.get('id', '0000'), status=200)


app = web.Application()
app.router.add_get('/', indexhandle)
app.router.add_get('/{id}', handle)

web.run_app(app, host='0.0.0.0', port=9977)



コード例 #55
0
async def check_handler(request) -> web.StreamResponse:
    return await broadcast_handler.check_handler(request)


@atomic
async def create_key_handler(request) -> web.StreamResponse:
    return await broadcast_handler.create_key_handler(request)


@atomic
async def post_raffle_handler(request) -> web.StreamResponse:
    return await broadcast_handler.post_raffle_handler(request)


loop.create_task(broadcast_handler.clean_rubbish())

tcp_core = asyncio.start_server(broadcast_handler.tcp_receiver_handle,
                                '0.0.0.0',
                                8002,
                                loop=loop)
loop.run_until_complete(tcp_core)

app = web.Application()
setup(app)

app.router.add_route('GET', '/check', check_handler)
app.router.add_route('GET', '/create_key', create_key_handler)
app.router.add_route('POST', '/post_raffle', post_raffle_handler)
app.on_shutdown.append(broadcast_handler.on_shutdown)
web.run_app(app, port=8001)
コード例 #56
0
def main():
    parser = argparse.ArgumentParser(
        prog="trveval",
        description=
        "Evaluate articles for relevance, updating the database as you go.",
        epilog=
        """Highlights are used to highlight terms in the Trove page. The file
        should contain "+" separated terms. The year can be of the form YYYY-MM-DD,
        with both days and months optional.""",
    )
    parser.add_argument(dest="database", help="The database to use.")
    parser.add_argument("-l",
                        "--highlights",
                        dest="highlights",
                        help="The file containing highlights.")
    parser.add_argument("-y",
                        "--year",
                        dest="year",
                        type=str,
                        help="Assess the given year only.")
    parser.add_argument(
        "-H",
        "--host",
        dest="host",
        help="Hostname of the app " + "[default %s]" % DEFAULT_HOST,
        default=DEFAULT_HOST,
    )
    parser.add_argument(
        "-P",
        "--port",
        dest="port",
        help="Port for the app " + "[default %s]" % DEFAULT_PORT,
        default=DEFAULT_PORT,
    )
    args = parser.parse_args()

    if args.highlights is None:
        highlights = ""
    else:
        if os.path.exists(args.highlights):
            # TODO: parse file and format
            with open(args.highlights, "r") as f:
                highlights = f.read()
        else:
            # TODO: Hopefully a string of plus separated terms
            highlights = args.highlights

    app = web.Application()
    app["websockets"] = weakref.WeakSet()
    app["dbname"] = args.database
    app["highlights"] = highlights
    app["year"] = args.year

    app.on_startup.append(on_startup)
    app.on_cleanup.append(on_cleanup)
    app.on_shutdown.append(on_shutdown)

    # app.add_routes([web.get("/", handle), web.get("/{name}", handle)])

    # Handler for websocket connections
    app.router.add_route("GET", "/ws", websocket_handler)

    # The articles page
    # TODO: Should be root
    app.router.add_route("GET", "/collector.html", handle_collector)

    # The assessment page
    app.router.add_route("GET", "/", handle_assessment)
    app.router.add_route("GET", "/assessment.html", handle_assessment)
    app.router.add_route("POST", "/", handle_post)
    app.router.add_route("POST", "/assessment.html", handle_post)

    # The articles page
    app.router.add_route("GET", "/articles.html", handle_articles)

    # The people page
    app.router.add_route("GET", "/people.html", handle_people)

    # The people page
    app.router.add_route("GET", "/queries.html", handle_queries)

    # static files
    static_path = os.path.join(os.path.dirname(__file__), "static")
    app.router.add_static("/static", static_path)

    # run the server
    web.run_app(app, host=args.host, port=args.port)
コード例 #57
0
                    // POST the information to /connect
                    let response = await fetch("/connect", {
                        method: "POST",
                        cache: "no-cache",
                        body: JSON.stringify(offer)
                    });

                    await conn.setRemoteDescription(await response.json());

                    console.log("Ready!");
                }
                connect();

            </script>
        </body>
    </html>
    """)


async def cleanup(app):
    await conn.close()


camera.close()  # Singletons like a camera are not awaited on close

app = web.Application()
app.add_routes(routes)
app.on_shutdown.append(cleanup)
web.run_app(app, host="0.0.0.0", port=8080)
コード例 #58
0
ファイル: app.py プロジェクト: saninstein/private-chat

async def static_processor(req):
    return {'STATIC_URL': '/static'}


sys.path.append(PATH)


def get_app():
    app = Application(middlewares=middlewares)
    app.on_shutdown.append(on_shutdown)

    app.client = AsyncIOMotorClient(MONGO_IP, MONGO_PORT)
    app.rooms = []

    aiohttp_session.setup(app, aiohttp_session.SimpleCookieStorage())
    aiohttp_jinja2.setup(app,
                         loader=FileSystemLoader(TEMPLATES_DIR),
                         context_processors=[static_processor])

    for route in routes:
        app.router.add_route(*route[1:], name=route[0])
    app.router.add_static('/static', 'static', name='static')
    return app


if __name__ == "__main__":
    app = get_app()
    web.run_app(app, host='127.0.0.1', port=80)
コード例 #59
0
ファイル: webhook.py プロジェクト: EasonC13/aio-telegram-bot
async def webhook_handle(request):
    bot = request.app["bot"]
    data = await request.text()
    await bot.process_update(json.loads(data))
    return web.Response()


async def init_bot(app: web.Application):
    bot = Bot(Client(TOKEN), handlers)
    await bot.initialize(webhook=True)
    await bot.client.set_webhook(f"https://{HOST}:{PORT}/{TOKEN}",
                                 certificate=SSL_PUBLIC_KEY)

    app["bot"] = bot

    yield

    await bot.client.delete_webhook()
    await bot.close()
    await bot.client.close()


app = web.Application()
app.router.add_post(f"/{TOKEN}", webhook_handle)
app.cleanup_ctx.extend([init_bot])

context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(SSL_PUBLIC_KEY, SSL_PRIVATE_KEY)

web.run_app(app, host="0.0.0.0", port=PORT, ssl_context=context)
コード例 #60
0
ファイル: manage.py プロジェクト: Steinerr/wg_test
def runserver():
    web.run_app(app, host='0.0.0.0', port=8080)