Beispiel #1
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
Beispiel #2
0
async def test_subapp_chained_config_dict_overriding(aiohttp_client) -> None:

    async def main_handler(request):
        assert request.config_dict['key'] == 'val1'
        return web.Response(status=200)

    root = web.Application()
    root['key'] = 'val1'
    root.add_routes([web.get('/', main_handler)])

    async def sub_handler(request):
        assert request.config_dict['key'] == 'val2'
        return web.Response(status=201)

    sub = web.Application()
    sub['key'] = 'val2'
    sub.add_routes([web.get('/', sub_handler)])
    root.add_subapp('/sub', sub)

    client = await aiohttp_client(root)

    resp = await client.get('/')
    assert resp.status == 200
    resp = await client.get('/sub/')
    assert resp.status == 201
Beispiel #3
0
    async def do(self,args):
        t = await self.setup()
        if args:
            dirs = []
            for a in args:
                try:
                    dirs.append(await t.subdir(a, create=False))
                except KeyError:
                    raise CommandError("'%s' does not exist"%(a,))
        else:
            dirs = [t]
        for tt in dirs:
            async for web in tt.tagged(WEBDATA, depth=self.options.this):
                path = web.path[len(WEBDATA_DIR):-1]
                if self.root.verbose == 2:
                    print('*','/'.join(path), sep='\t',file=self.stdout)
                    for k,v in r_show(web,''):
                        print(k,v, sep='\t',file=self.stdout)

                elif self.root.verbose > 1:
                    dump({'/'.join(path):r_dict(dict(web))}, stream=self.stdout)
                else:
                    path = '/'.join(path)
                    name = web.get('name','-')
                    if name == path:
                        name = "-"
                    print(path,name,web.get('descr','-'), sep='\t',file=self.stdout)
Beispiel #4
0
async def get_application():
    app = web.Application()
    app.add_routes([
        web.get("/fire", fire),
        web.get("/metrics", metrics),
    ])
    app["counter"] = Counter("reqs", "Reqs counter", ["view"])
    return app
Beispiel #5
0
def init():
    app = web.Application()
    app.router.add_routes([
        web.get('/', intro),
        web.get('/simple', simple),
        web.get('/change_body', change_body),
        web.get('/hello/{name}', hello),
        web.get('/hello', hello),
    ])
    return app
Beispiel #6
0
 def __init__(self, *, loop):
     self.loop = loop
     self.app = web.Application(loop=loop)
     self.app.router.add_routes(
         [web.get('/v2.7/me', self.on_me),
          web.get('/v2.7/me/friends', self.on_my_friends)])
     self.runner = None
     here = pathlib.Path(__file__)
     ssl_cert = here.parent / 'server.crt'
     ssl_key = here.parent / 'server.key'
     self.ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
     self.ssl_context.load_cert_chain(str(ssl_cert), str(ssl_key))
async def start():
    await communionserver._start()
    app = web.Application()
    app.add_routes([
        web.get('/{tail:.*}', handler),
    ])

    # Configure default CORS settings.
    cors = aiohttp_cors.setup(app, defaults={
        "*": aiohttp_cors.ResourceOptions(
                allow_credentials=True,
                expose_headers="*",
                allow_headers="*",
                allow_methods=["GET", ]
            )
    })

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

    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, ADDRESS, PORT)
    await site.start()
Beispiel #8
0
    async def serve_rest(self):
        global web
        from aiohttp import web
        import aiohttp_cors
        app = web.Application()
        app.add_routes([
            web.get('/{tail:.*}', self._handle_get),
            web.put('/{tail:.*}', self._handle_put),
            web.patch('/{tail:.*}', self._handle_equilibrate),
        ])

        # Configure default CORS settings.
        cors = aiohttp_cors.setup(app, defaults={
            "*": aiohttp_cors.ResourceOptions(
                    allow_credentials=True,
                    expose_headers="*",
                    allow_headers="*",
                    allow_methods=["GET", "PATCH", "PUT"]
                )
        })

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

        runner = web.AppRunner(app)
        await runner.setup()
        site = web.TCPSite(runner, self.address, self.rest_port) #TODO: try more ports
        await site.start()
        print("Opened the seamless REST server at port {0}".format(self.rest_port))
Beispiel #9
0
def run(**kwargs):
    host = kwargs['host']
    port = kwargs['port']

    app = web.Application()
    app.add_routes([
        web.get('/', index_handler),
        web.get('/sse', sse_handler),
        web.get('/pub', push_message_handler)
    ])

    app.on_shutdown.append(_shutdown)

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

    web.run_app(app, host=host, port=port)
Beispiel #10
0
async def server(*args, **kwargs):
    for pulp_plugin in pulp_plugin_configs():
        if pulp_plugin.name != "pulpcore.app":
            content_module_name = '{name}.{module}'.format(name=pulp_plugin.name,
                                                           module=CONTENT_MODULE_NAME)
            with suppress(ModuleNotFoundError):
                import_module(content_module_name)
    app.add_routes([web.get(settings.CONTENT_PATH_PREFIX + '{path:.+}', Handler().stream_content)])
    return app
Beispiel #11
0
 async def do(self,args):
     t = await self.setup()
     if args:
         if self.options.all:
             raise CommandError("Arguments and '-a' are mutually exclusive")
         dirs = []
         for a in args:
             dirs.append(await t.subdir(a, create=False))
         verbose = True
     else:
         dirs = [t]
         verbose = self.options.all
     for tt in dirs:
         async for web in tt.tagged(WEBSERVER):
             path = web.path[len(WEBSERVER_DIR):-1]
             if verbose:
                 dump({path: r_dict(dict(web))}, stream=self.stdout)
             else:
                 print('/'.join(path), web.get('host','-'), web.get('port',80), web.get('default','default'), web.get('descr',''), sep='\t',file=self.stdout)
Beispiel #12
0
def main():
    """
        Main method for server redirector
    """
    app = web.Application()
    handler = HTTPSRedirecter()
    app.add_routes([
        web.get("/{tail:.*}", handler.all),
        web.post("/{tail:.*}", handler.all),
        web.head("/{tail:.*}", handler.all)
    ])
    web.run_app(app, port=80)
Beispiel #13
0
def test_get(router):
    async def handler(request):
        pass

    router.add_routes([web.get('/', handler)])
    assert len(router.routes()) == 2  # GET and HEAD

    route = list(router.routes())[1]
    assert route.handler is handler
    assert route.method == 'GET'
    assert str(route.url_for()) == '/'

    route2 = list(router.routes())[0]
    assert route2.handler is handler
    assert route2.method == 'HEAD'
Beispiel #14
0
def main(argv: List[str]):
    opts = parse_args(argv)

    if opts.subparser_name == 'server':
        ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
        ssl_context.load_cert_chain(opts.cert, opts.key)
        ssl_context.check_hostname = False
        ssl_context.verify_mode = ssl.CERT_NONE

        auth = basic_auth_middleware(json.load(open(opts.password_db)))
        app = web.Application(middlewares=[auth],
                              client_max_size=MAX_FILE_SIZE)
        app.add_routes([web.put('/archives', functools.partial(handle_put, opts.storage_folder, opts.min_free_space)),
                        web.get('/list', functools.partial(handle_list, opts.storage_folder)),
                        web.post('/get', functools.partial(handle_get, opts.storage_folder)),
                        web.post('/del', functools.partial(handle_del, opts.storage_folder))])

        host, port = opts.addr.split(":")

        web.run_app(app, host=host, port=int(port), ssl_context=ssl_context)
    elif opts.subparser_name == 'user_add':
        if os.path.exists(opts.db):
            db = json.load(open(opts.db))
        else:
            db = {}

        if opts.password is None:
            if opts.user not in db:
                print("User not in db yet, provide password")
                exit(1)
            enc_password, salt, _ = db[opts.user]
        else:
            enc_password, salt = encrypt_password(opts.password)
        db[opts.user] = [enc_password, salt, opts.role]
        js = json.dumps(db, indent=4, sort_keys=True)
        open(opts.db, "w").write(js)
    else:
        assert opts.subparser_name == 'user_rm'
        db = json.load(open(opts.db))

        if opts.user not in db:
            exit(0)
        del db[opts.user]

        js = json.dumps(db, indent=4, sort_keys=True)
        open(opts.db, "w").write(js)
Beispiel #15
0
    def build_webserver(self, hooks):
        '''
        Build an async web server used by hooks
        '''
        app = web.Application()

        # Always add a simple test endpoint
        async def ping(request):
            return web.Response(text='pong')

        app.add_routes([web.get('/ping', ping)])

        # Add routes from hooks
        for hook in hooks:
            app.add_routes(hook.routes)

        # Finally build the webserver coroutine
        return web._run_app(app, port=self.http_port, print=logger.info)
Beispiel #16
0
def main():
    parser = argparse.ArgumentParser(
        description='A webserver based on aiohttp.')
    parser.add_argument(
        '--uvloop', dest='uvloop', action='store_const', const=True,
        help='use uvloop.')
    args = parser.parse_args()

    app = web.Application()
    app.add_routes([
        web.get('/', hello_handler)
    ])

    if args.uvloop:
        print('running the uvloop...')
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

    web.run_app(app, host='127.0.0.1', port=8381)
Beispiel #17
0
 def create_app(self, e):
     with e['webserver'].create_subapp('/prefix') as app:
         app.add_routes([web.get('/', self.request_handler)])
Beispiel #18
0
                await ws.close()
            else:
                # そうでないなら、クライアントに対して文字を反射する
                await ws.send_str(msg.data + '/answer')
        elif msg.type == aiohttp.WSMsgType.ERROR:
            print('ws connection closed with exception %s' %
                  ws.exception())

    # 例外による切断 あるいは closeを検知したのだからクライアントリストから抜く
    ws_clients.remove(ws)
    print('websocket connection closed')
    return ws

# HTTPd用のルーティング設定
routes = [
    web.get("/", web_hello),
    web.get("/connect", web_connect),
]

if __name__ == "__main__":
    # グローバルにループイベントを作成
    loop = asyncio.get_event_loop()

    # aiohttp.web.Applicationの実体化
    app = web.Application()
    app.add_routes(routes)
    runner = web.AppRunner(app)
    loop.run_until_complete(runner.setup())

    site = web.TCPSite(runner, port=bindPort)
Beispiel #19
0
        logger.info('trying to establish connection after 2 sec')
        await asyncio.sleep(2)


async def on_app_close(application: Application):
    try:
        if application['rabbit']:
            await application['rabbit'].close()
            logger.info('rabbitmq connection closed')
        await application['redis'].close()
        await application['redis'].wait_closed()
        logger.info('redis connection closed')
        application['db'].close()
        logger.info('db connection closed')
    except (Exception, ConnectionError) as e:
        logger.info(f'trying to reconnect: {e}')
        await asyncio.sleep(2)

app = Application(loop=loop)
app.on_startup.append(on_start_up)
app.on_shutdown.append(on_app_close)

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

app.add_routes([web.get('/', health_check)])
app.add_routes(user_routes)

if not DEBUG:
    run_app(app=app, port=8030)
Beispiel #20
0
 def __init__(self, config):
     db = Gino(model_classes=tuple(gtfs_model.tables))
     app = web.Application(middlewares=[db])
     # I don't quite get why aiohttp says I shouldn't just use self.config
     # for this, but whatever
     app["config"] = config
     app["aiocache"] = SimpleMemoryCache()
     app["ansiconv"] = ansi2html.converter.Ansi2HTMLConverter(linkify=True,
                                                              title="curlbus",
                                                              font_size='16px')
     app['siriclient'] = SIRIClient(config["mot"]["url"],
                                    config["mot"]["user_id"])
     db.init_app(app)
     app.router.add_static("/static/", os.path.join(os.path.dirname(__file__), '..', "static"))
     app.add_routes([web.get('/{stop_code:\d+}{tail:/*}', self.handle_station),
                     web.get('/operators{tail:/*}', self.handle_operator_index),
                     web.get('/nearby', self.handle_nearby),
                     web.get('/{operator:\w+}{tail:/*}', self.handle_operator),
                     web.get('/rail/stations{tail:/*}', self.handle_rail_stations),
                     web.get('/rail/map{tail:/*}', self.handle_rail_map),
                     web.get('/operators/{operator}/{route_number}{tail:/*}', self.handle_route),
                     web.get('/operators/{operator}/{route_number}/{alternative}{tail:/*}', self.handle_route),
                     web.get('/operators/{operator}{tail:/*}', self.handle_operator),
                     web.get('/{operator}/{route_number}{tail:/*}', self.handle_route),
                     web.get('/{operator}/{route_number}/{alternative}{tail:/*}', self.handle_route),
                     web.get('/{tail:/*}', self.handle_index)])
     self._app = app
Beispiel #21
0
from aiohttp import web
from db import init_pg, close_pg


async def hello(request):
    return web.Response(text="Hello, world")


app = web.Application()
app.add_routes([web.get('/', hello)])
app.on_startup.append(init_pg)
app.on_cleanup.append(close_pg)

if __name__ == '__main__':
    web.run_app(app)
Beispiel #22
0
from aiohttp import web

import views

app = web.Application()
app.add_routes([
    web.get('/ping', views.ping),
    web.get('/mail-horoscope', views.get_horo),
    web.get('/', views.main)
])
Beispiel #23
0

async def token_listen(request: web.Request):
    print("Got token")
    access_token = request.rel_url.query['access_token']
    user_id = int(request.rel_url.query['state'])
    user = await get_user(user_id)
    user.mosreg_token = access_token
    await user.push_changes()
    await bot.send_message(
        InputUser(user.user_id, user.access_hash),
        "✅Аккаунт привязан!✅\nОтправь /start чтобы "
        "открыть меню")
    return web.Response(status=200)


app = web.Application()
app.add_routes([
    web.get("/get_request", get_request),
    web.get("/token_listen", token_listen),
])


async def main():
    await bot.start()
    task = web._run_app(app, shutdown_timeout=60.0, backlog=128, port=8050)
    await asyncio.gather(task)


loop.run_until_complete(main())
Beispiel #24
0
async def web_results_by_id(request: web.Request):
    id = request.match_info["id"]
    if not id:
        return web.Response(text="Resource not found", status=404)

    res = resultall.getLastResultById(id)
    if not res:
        return web.Response(text="Resource not found", status=404)

    sd = SimpleTextLineTestDecorator()
    html = sd.render(res)
    return web.Response(text=html, content_type="text/html")


routes = [
    web.get   ("/", web_top),
    web.get("/logs", web_log),
    web.get("/reset", web_reset),
    web.get("/scenarios", web_list_scenarios),
    web.get("/scenarios/{id}", web_detail_scenarios),
    web.get("/run/id/{id}", web_run_by_id),
    web.get("/results/{id}", web_results_by_id),
    web.static("/static", "./static"),
]


# Jinja2 Filter: ログの整形用
def j2_filter_date(date: datetime):
    return date.strftime('%H:%M:%S.%f')

j2_filters = dict()
Beispiel #25
0
from aiohttp import web


async def demo_api(request):
    print(".")
    print(request.query_string)
    return web.Response(text="OK")


if __name__ == '__main__':
    app = web.Application()
    app.add_routes(
        [web.get("/{tail:.*}", demo_api),
         web.post("/{tail:.*}", demo_api)])

    web.run_app(app, host="127.0.0.1", port=5000)
Beispiel #26
0
    async def send_message(self, sender_id, message_text):

        params = {"access_token": PAGE_ACCESS_TOKEN}
        headers = {"Content-Type": "application/json"}
        data = json.dumps({
            "recipient": {
                "id": sender_id
            },
            "message": {
                "text": message_text
            }
        })

        async with aiohttp.ClientSession() as session:
            await session.post("https://graph.facebook.com/v3.0/me/messages",
                               params=params,
                               headers=headers,
                               data=data)


routes = [
    web.get('/', BotControl, name='verify'),
    web.post('/', BotControl, name='webhook'),
]

app = web.Application()
app.add_routes(routes)

#if __name__ == '__main__':
#web.run_app(app, host='0.0.0.0', port=environ.get("PORT", 9090))
Beispiel #27
0
    """
    :type request: web.Request
    """
    data = request.query
    # Data validation can be traded for performance
    # Checking that only valid parameters supplied
    if len(data.keys() & {"id", "tag"}) == 2 and len(data) == 2:
        # Insert data in redis
        id_value = data.get("id")
        tag_value = data.get("tag")
        # Checking parameters
        if id_value.isalnum() and tag_value.isalnum():
            data_formatted = id_value + "&" + tag_value
            await app['redis'].execute('incr', data_formatted)
            status = 202
            message = "OK"
        else:
            status = 400
            message = "Parameters should only contain (a-z, A-Z and 0-9)"
    else:
        status = 400
        message = "Should only contain \"id\" and \"tag\" parameters"
    return web.Response(status=status, text=message)


app = web.Application()
app.add_routes([web.get('/', handler)])
app.on_startup.append(create_redis_pool)
app.on_shutdown.append(destroy_redis_pool)
web.run_app(app)
Beispiel #28
0
#*****************************************************************************************************************************************


@aiohttp_jinja2.template('user_dashboard.jinja2')
async def user_dashboard(request):
    return


#*****************************************************************************************************************************************
# App start up code below here only
#*****************************************************************************************************************************************


async def on_startup(userapi):
    #log.info("org sub_app startup")
    print("user_controller sub_app startup")


async def on_shutdown(userapi):
    #log.info("org sub_app shutdown")
    print("user_controller sub_app shutdown")


user_controller = web.Application()
log = logging.getLogger(__name__)

user_controller.on_shutdown.append(on_shutdown)
user_controller.on_startup.append(on_startup)
user_controller.add_routes(
    [web.get('/', user_dashboard, name='user_dashboard')])
Beispiel #29
0
        'price': 30.0
    }]
}


async def event(request):
    assert request.match_info['category'] == 'foo'
    assert request.match_info['event'] == 'bar'
    return json_response(event_data)


async def on_prepare(request, response):
    response.headers['Access-Control-Allow-Origin'] = '*'


app = web.Application()
app.on_response_prepare.append(on_prepare)
app.add_routes([
    web.get('/api/', root),
    web.get('/api/events/{category}/{event}/', event),
])

hdlr = logging.StreamHandler()
hdlr.setLevel(logging.INFO)
hdlr.setFormatter(logging.Formatter(fmt='%(message)s', datefmt='%H:%M:%S'))
logger = logging.getLogger('aiohttp')
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)

web.run_app(app, port=8000, print=lambda x: None)
Beispiel #30
0
from aiohttp import web
from .db import redis


async def handleGet(request):
    id = request.match_info.get('id')
    res = await redis.get_data_by_user(app, id)
    return web.json_response({'user': id, 'data': res})


async def handlePost(request):
    try:
        data = await request.post()
    except Exception as ex:
        print(ex)
    if not data.get('id'):
        return web.json_response({'error': 'No id provided in post request'})
    if not data.get('data'):
        return web.json_response({'error': 'No data provided in post request'})
    res = await redis.save_data(app, data['id'], data['data'])
    if res:
        return web.json_response({'status': True})
    return web.json_response(
        {'error': 'Error while inserting data in redis. Try again later'})


app = web.Application()
app.on_startup.append(redis.connect_redis)
app.on_cleanup.append(redis.close_redis)
app.add_routes([web.get('/{id}', handleGet), web.post('/save', handlePost)])
Beispiel #31
0
                    parse_result['summary'] = 'No Summary'
                parse_result['link'] = entry['link']
                parse_result['published'] = entry['published']
                parse_result['category'] = trends_data[0]
                all_results.append(parse_result)
    return all_results


async def main(request):
    result = await trends_parse(topics)
    parsed_data = list()
    for file in result:
        parsed_data.append([
            file['title'], file['summary'], file['link'], file['published'],
            file['category']
        ])
    context = {'data': parsed_data}
    response = aiohttp_jinja2.render_template('index.html', request, context)
    return response


app = web.Application()

app.add_routes([web.get('/', main)])

aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates'))
app.router.add_static('/static', 'static', name='static')
jenv = app.get('aiohttp_jinja2_environment')

web.run_app(app, host='127.0.0.1', port=8000)
Beispiel #32
0
 def setup_routes(self):
     self.app.add_routes([
         web.get('', self.get_overlays),
         web.get('/statistics', self.get_statistics),
         web.post('/statistics', self.enable_statistics)
     ])
Beispiel #33
0
 def add_get():
     routes.append(web.get(method.__getattribute__("path"), method, allow_head=False))
Beispiel #34
0
from aiohttp import web
from chat.views import CreateUser, Login, Logout, WebSocket, RoomChat

routes = [
    web.get('/', Login, name='homepage'),
    web.get('/createuser', CreateUser, name='createuser'),
    web.post('/createuser', CreateUser),
    web.post('/login', Login, name='login'),
    web.get('/logout', Logout, name='logout'),
    web.get('/room_chat', RoomChat, name='room_chat'),
    web.get('/ws', WebSocket)
]
 def setup_routes(self):
     self.app.add_routes(
         [web.get('', self.handle_get),
          web.post('', self.handle_post)])
Beispiel #36
0
'''Вспомогательная функция получения последнего заказа'''
def get_latest_order():
    sql_query = 'select max(id) from orders'
    result = sql_engine.execute(sql_query)
    latest_order = result.fetchall()[0][0]
    return latest_order


'''SQL INIT'''
PATH_TO_SQL = 'mysql+pymysql://newuser:password@localhost:3306/bookstore'
'''Формат пути = СУБД+Диалект://Имя_пользователя:пароль@адрес_сервера:порт/название_БД'''
sql_engine = create_engine(PATH_TO_SQL, pool_recycle=3600)
metadata = MetaData()
books = Table('books', metadata, autoload=True, autoload_with=sql_engine)
shops = Table('shops', metadata, autoload=True, autoload_with=sql_engine)
orders = Table('orders', metadata, autoload=True, autoload_with=sql_engine)
users = Table('users', metadata, autoload=True, autoload_with=sql_engine)
orderitems = Table('orderitems', metadata, autoload=True, autoload_with=sql_engine)
stocks = Table('stocks', metadata, autoload=True, autoload_with=sql_engine)
'''SQL INIT'''

'''AIOHTTP SERVER INIT'''
app = web.Application()
routes = [web.get('/user/{id}', get_user),
          web.get('/history/{user}', get_purchase_history),
          web.get('/stock/{shop}', get_shop_stock),
          web.post('/neworder', post_order)]
app.add_routes(routes)
web.run_app(app)
'''AIOHTTP SERVER INIT'''
Beispiel #37
0
def main():
    app = web.Application()
    app.add_routes([web.get('/', client_handler)])
    app.add_routes([web.get('/ws', websocket_handler)])
    web.run_app(app)
Beispiel #38
0
    return web.Response(text='Hello, world')


async def four_hundred_one(request):
    return web.HTTPUnauthorized(reason="I must simulate errors.",
                                text="Simulated server error.")


async def five_hundred(request):
    return web.HTTPInternalServerError(reason="I must simulate errors.",
                                       text="Simulated server error.")


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

rabbit_util = RabbitUtil(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('/publish', publish_msg)])

runner = web.AppRunner(app)
loop.run_until_complete(runner.setup())
site = web.TCPSite(runner, 'localhost', 5102)

loop.run_until_complete(site.start())
loop.run_forever()
Beispiel #39
0
 def __init__(self):
     self.fp_interface = FingerprintInterface()
     self.app = web.Application()
     self.app.router.add_routes([web.post('/', self.rpc),
                         web.get('/enroll/{uid}', self.enroll),
                         web.get('/identify', self.identify)])
Beispiel #40
0
async def init_app():
    """ Initialize the main application instance and return it"""
    async def close_redis(app):
        """Close redis connections"""
        log.server_logger.info('Closing redis connections')
        app['rdata'].close()

    async def open_redis(app):
        """Open redis connections"""
        log.server_logger.info("Opening redis connections")
        app['rdata'] = await aioredis.create_redis_pool(
            (redis_host, redis_port),
            db=int(os.getenv('REDIS_DB', '2')),
            encoding='utf-8',
            minsize=2,
            maxsize=15)
        # Global vars
        app['clients'] = {}  # Keep track of connected clients
        app['last_msg'] = {}  # Last time a client has sent a message
        app['active_messages'] = set(
        )  # Avoid duplicate messages from being processes simultaneously
        app['cur_prefs'] = {}  # Client currency preferences
        app['subscriptions'] = {
        }  # Store subscription UUIDs, this is used for targeting callback accounts
        app['active_work'] = set(
        )  # Keep track of active work requests to prevent duplicates

    # Setup logger
    if debug_mode:
        logging.basicConfig(level=logging.DEBUG)
    else:
        root = logging.getLogger('aiohttp.server')
        logging.basicConfig(level=logging.INFO)
        if options.log_to_stdout:
            handler = logging.StreamHandler(sys.stdout)
            formatter = logging.Formatter(
                "%(asctime)s;%(levelname)s;%(message)s",
                "%Y-%m-%d %H:%M:%S %z")
            handler.setFormatter(formatter)
            root.addHandler(handler)
        else:
            handler = WatchedFileHandler(log_file)
            formatter = logging.Formatter(
                "%(asctime)s;%(levelname)s;%(message)s",
                "%Y-%m-%d %H:%M:%S %z")
            handler.setFormatter(formatter)
            root.addHandler(handler)
            root.addHandler(
                TimedRotatingFileHandler(log_file,
                                         when="d",
                                         interval=1,
                                         backupCount=100))

    app = web.Application()
    cors = aiohttp_cors.setup(app,
                              defaults={
                                  "*":
                                  aiohttp_cors.ResourceOptions(
                                      allow_credentials=True,
                                      expose_headers="*",
                                      allow_headers="*",
                                  )
                              })
    app.add_routes([web.get('/', websocket_handler)])  # All WS requests
    app.add_routes([web.post('/callback',
                             callback)])  # HTTP Callback from node
    # HTTP API
    users_resource = cors.add(app.router.add_resource("/api"))
    cors.add(users_resource.add_route("POST", http_api))
    alerts_resource = cors.add(app.router.add_resource("/alerts/{lang}"))
    cors.add(alerts_resource.add_route("GET", alerts_api))
    #app.add_routes([web.post('/callback', callback)])
    app.on_startup.append(open_redis)
    app.on_shutdown.append(close_redis)

    return app
Beispiel #41
0
function from aioprometheus is called to format the metrics into the
appropriate format.
"""

from aiohttp import web
from aiohttp.hdrs import ACCEPT
from aioprometheus import render, Counter, Registry


app = web.Application()
app.registry = Registry()
app.events_counter = Counter("events", "Number of events.")
app.registry.register(app.events_counter)


async def handle_root(request):
    app.events_counter.inc({"path": "/"})
    text = "Hello aiohttp"
    return web.Response(text=text)


async def handle_metrics(request):
    content, http_headers = render(app.registry, request.headers.getall(ACCEPT, []))
    return web.Response(body=content, headers=http_headers)


app.add_routes([web.get("/", handle_root), web.get("/metrics", handle_metrics)])


web.run_app(app)
Beispiel #42
0
                    return web.Response(text=data, headers=self.headers)
            else:
                raise web.HTTPNotFound()


def main():
    host = 'localhost'
    port = '9095'
    if len(sys.argv) > 1:
        config = sys.argv[1]
        if ':' in config:
            host, port = config.split(':')
        elif '.' in config:
            host = config
        else:
            port = config

    web.run_app(app, host=host, port=int(port))


handler = Handler()
app = web.Application()
app.add_routes([
    web.get('/hanger/sleep/', handler.handle_sleep),
    web.post('/hanger/open/', handler.handle_open_slot),
    web.post('/hanger/{key}/write/', handler.handle_write_slot),
    web.post('/hanger/{key}/read/', handler.handle_read_slot),
])

if __name__ == '__main__':
    main()
Beispiel #43
0
            })

        # TODO: Fix total score after challenge
        for p in self.players:
            self.last_score[p] = scores[p]
            self.scores[p] += scores[p]

        await self.broadcast_names()
        self.state = REVIEWING


async def websocket_handler(request):
    ws = web.WebSocketResponse()
    stahp = app["stahp"]
    await ws.prepare(request)
    await stahp.handle_player(ws)
    return ws


async def on_startup(app):
    app["stahp"] = Stahp()


app = web.Application()
app.on_startup.append(on_startup)
app.add_routes([web.get("/ws", websocket_handler)])

if __name__ == "__main__":
    logging.basicConfig(level="INFO")
    web.run_app(app, port=9999)
Beispiel #44
0
    async def listen_backchannel(self, backchannel_port):
        """
        Setup the routes to allow the test harness to send commands to and get replies
        from the Agent under test.

        Expected topics include:

            schema                 GET to return a list and POST to create/update
            credential-definition  GET to return a list and POST to create/update
            connection             GET to return a list or single; POST to create/update*
            issue-credential       GET to return a list or single; POST to create/update*
            credential             GET to return a list of single from wallet; POST to remove*
            proof                  GET to return a list or single; POST to create/update*

        GET with no parameters returns all
        GET with an "id" parameter will return a single record
        POST will submit a JSON payload
        POST* will contain an "operation" element within the payload to define the operation
        POST operations on existing records must contain an "id" element
        POST operations will contain a "data" element which is the payload to pass through to the agent

        E.g.:  POST to /agent/command/issue_credential { "operation":"send-proposal", "data":"{...}"}
        E.g.:  POST to /agent/command/issue_credential { "operation":"issue", "id":"<cred exch id>", "data":"{...}"}

        Operations for each topic are in the backchannel_operations.csv file, generated from
        the Google sheet at https://bit.ly/AriesTestHarnessScenarios
        """
        # operations_file = "../backchannel_operations.txt"
        # self.operations = read_operations(file_name=operations_file, parser="pipe")
        operations_file = "./backchannel_operations.csv"
        self.operations = read_operations(file_name=operations_file)

        app = web.Application()
        app.add_routes([
            web.post("/agent/command/{topic}/", self._post_command_backchannel)
        ])
        app.add_routes([
            web.post("/agent/command/{topic}", self._post_command_backchannel)
        ])
        app.add_routes([
            web.post(
                "/agent/command/{topic}/{operation}/",
                self._post_command_backchannel,
            )
        ])
        app.add_routes([
            web.post("/agent/command/{topic}/{operation}",
                     self._post_command_backchannel)
        ])
        app.add_routes([
            web.get("/agent/command/{topic}/", self._get_command_backchannel)
        ])
        app.add_routes(
            [web.get("/agent/command/{topic}", self._get_command_backchannel)])
        app.add_routes([
            web.get("/agent/command/{topic}/{id}/",
                    self._get_command_backchannel)
        ])
        app.add_routes([
            web.get("/agent/command/{topic}/{id}",
                    self._get_command_backchannel)
        ])
        app.add_routes([
            web.get(
                "/agent/command/{topic}/{operation}/{id}/",
                self._get_command_backchannel,
            )
        ])
        app.add_routes([
            web.get(
                "/agent/command/{topic}/{operation}/{id}",
                self._get_command_backchannel,
            )
        ])
        app.add_routes([
            web.delete("/agent/command/{topic}/{id}/",
                       self._delete_command_backchannel)
        ])
        app.add_routes([
            web.delete("/agent/command/{topic}/{id}",
                       self._delete_command_backchannel)
        ])
        app.add_routes([
            web.get("/agent/response/{topic}/", self._get_response_backchannel)
        ])
        app.add_routes([
            web.get("/agent/response/{topic}", self._get_response_backchannel)
        ])
        app.add_routes([
            web.get("/agent/response/{topic}/{id}/",
                    self._get_response_backchannel)
        ])
        app.add_routes([
            web.get("/agent/response/{topic}/{id}",
                    self._get_response_backchannel)
        ])
        runner = web.AppRunner(app)
        await runner.setup()
        self.backchannel_site = web.TCPSite(runner, "0.0.0.0",
                                            backchannel_port)
        await self.backchannel_site.start()
        print("Listening to backchannel on port", backchannel_port)
Beispiel #45
0
    server = web.Server(serveConsolePage)
    await asyncio.get_event_loop().create_server(server, "", 8081)
    print("======= Serving on http://127.0.0.1:8080/ ======")
    # pause here for very long time by serving HTTP requests and
    # waiting for keyboard interruption
    # await asyncio.sleep(100*3600)

    tasks = [control(), start_server]
    # web.run_app(app)
    await asyncio.gather(*tasks)


# ==============================
from aiohttp import web


async def serveConsolePage(request):
    # return web.Response(text="serveConsolePage, world")
    return web.FileResponse('websocketTests/zones.html')


app = web.Application()
app.add_routes([web.get('/', serveConsolePage)])


# ===================================
if __name__ == "__main__":
    ioloop = asyncio.get_event_loop()
    ioloop.run_until_complete(main())
    ioloop.close()
Beispiel #46
0
import asyncio

from aiohttp import web


async def hello_handler(request):
    """Root handler."""
    try:
        duration = int(request.query['duration'])
    except (KeyError, ValueError):
        duration = 0

    if duration:
        await asyncio.sleep(duration / 1000)

    return web.Response(text='Hello world.')


app = web.Application()
app.add_routes([
    web.get('/', hello_handler)
])


def main():
    web.run_app(app, host='127.0.0.1', port=8381)


if __name__ == '__main__':
    main()
Beispiel #47
0
from aiohttp import web


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)
Beispiel #48
0
 def setup_routes(self):
     self.app.add_routes([
         web.get('/tribler', self.get_tribler_stats),
         web.get('/ipv8', self.get_ipv8_stats)
     ])
Beispiel #49
0
from aiohttp import web

from pulpcore.content import app
from pulp_docker.app.registry import Registry

registry = Registry()

app.add_routes([web.get('/v2/', Registry.serve_v2)])
app.add_routes([web.get(r'/v2/{path:.+}/blobs/sha256:{digest:.+}', registry.get_by_digest)])
app.add_routes([web.get(r'/v2/{path:.+}/manifests/sha256:{digest:.+}', registry.get_by_digest)])
app.add_routes([web.get(r'/v2/{path:.+}/manifests/{tag_name}', registry.get_tag)])
app.add_routes([web.get(r'/v2/{path:.+}/tags/list', registry.tags_list)])
Beispiel #50
0
 async def make_app():
     app = web.Application()
     app.add_routes([web.get('/', websocket_handler)])
     return app
Beispiel #51
0
async def get_application():
    app = web.Application()
    app.add_routes([web.get("/fire", fire)])
    app.cleanup_ctx.append(statsd_client)
    return app
Beispiel #52
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)
])

if __name__ == '__main__':
    web.run_app(app)
Beispiel #53
0
    ws_clients.remove(ws)
    print('websocket connection closed')

    return ws

async def web_log(request: web.Request):
    args = dict()
    args["logs"] = logs.get_logs()
    return aiohttp_jinja2.render_template("templ/status.templ", request, args)

async def web_view(request: web.Request):
    args = dict()
    return aiohttp_jinja2.render_template("templ/view.html", request, args)

routes = [
    web.get   ("/", web_hello),
    web.get("/logs", web_log),
    web.get("/connect", web_connect),
    web.get("/view", web_view),
    web.static("/static", "./static"),
]


# Jinja2 Filter: ログの整形用
def j2_filter_date(date: datetime):
    return date.strftime('%H:%M:%S.%f')

j2_filters = dict()
j2_filters["strftime"] = j2_filter_date

app = web.Application()
    async def make_application(self) -> web.Application:
        """Get the aiohttp application instance."""
        middlewares = []
        stats: Collector = await self.context.inject(Collector, required=False)
        if stats:

            @web.middleware
            async def collect_stats(request, handler):
                handler = stats.wrap_coro(
                    handler, [handler.__qualname__, "any-admin-request"])
                return await handler(request)

            middlewares.append(collect_stats)

        app = web.Application(middlewares=middlewares)
        app["request_context"] = self.context
        app["outbound_message_router"] = self.responder.send

        app.add_routes([
            web.get("/", self.redirect_handler),
            web.get("/modules", self.modules_handler),
            web.get("/status", self.status_handler),
            web.post("/status/reset", self.status_reset_handler),
            web.get("/ws", self.websocket_handler),
        ])
        await register_module_routes(app)

        for protocol_module_path in self.context.settings.get(
                "external_protocols", []):
            try:
                routes_module = ClassLoader.load_module(
                    f"{protocol_module_path}.routes")
                await routes_module.register(app)
            except Exception as e:
                raise ConfigError(
                    f"Failed to load external protocol module '{protocol_module_path}'."
                ) from e

        cors = aiohttp_cors.setup(
            app,
            defaults={
                "*":
                aiohttp_cors.ResourceOptions(
                    allow_credentials=True,
                    expose_headers="*",
                    allow_headers="*",
                    allow_methods="*",
                )
            },
        )
        for route in app.router.routes():
            cors.add(route)

        setup_aiohttp_apispec(
            app=app,
            title="Aries Cloud Agent",
            version="v1",
            swagger_path="/api/doc",
        )
        app.on_startup.append(self.on_startup)
        return app
Beispiel #55
0
from torpeewee import *
from aiohttp import web

db = MySQLDatabase("test", host="127.0.0.1", user="******", passwd="123456")

class BaseModel(Model):
    class Meta:
        database = db

class Test(BaseModel):
    id = IntegerField(primary_key= True)
    data = CharField(max_length=64, null=False)
    created_at = DateTimeField()

async def show_handle(request):
    datas = [t.data for t in await Test.select()]
    return web.Response(text = u"<br />".join(datas))

async def create_handle(request):
    data = await request.post()
    data = data["data"]
    await Test.create(data=data, created_at=datetime.datetime.now())
    return web.HTTPFound('/')

app = web.Application()
app.add_routes([
    web.get('/', show_handle),
    web.post('/', create_handle)
])

web.run_app(app)
Beispiel #56
0
# 
from tick.src.tick import (
  _tick_,
  tick_all,
  plot
)


#
from aiohttp import web

#
app_tick = web.Application()

#
app_tick.add_routes([

  web.get('/',   _tick_),
  web.get('/all', tick_all),
  web.post('/plot', plot)
  
])
    try:
        limit = int(request.query.get("limit", -1))
        offset = int(request.query.get("offset", 0))
    except ValueError as e:
        error_message = {"error": e.args[0]}
        return web.json_response(error_message)

    links = await search(q, limit, offset)

    return web.json_response(links)


async def search(q, limit=None, offset=0):
    async with Elasticsearch() as es:
        body = {"query": {"match": {"body": q}}}
        scan = await es.search(size=limit,
                               from_=offset,
                               index="_all",
                               doc_type="crawler_links",
                               body=body)
        print(scan)
        docs = scan["hits"]["hits"]
        return [doc["_source"]["link"] for doc in docs]


app = web.Application()
app.add_routes([web.get("/api/v1/search/", handle)])

web.run_app(app)
Beispiel #58
0
 def __init__(self, config):
     db = Gino(model_classes=tuple(gtfs_model.tables))
     app = web.Application(middlewares=[db])
     # I don't quite get why aiohttp says I shouldn't just use self.config
     # for this, but whatever
     app["config"] = config
     app["aiocache"] = SimpleMemoryCache()
     app["ansiconv"] = ansi2html.converter.Ansi2HTMLConverter(
         linkify=True, title="curlbus", font_size='16px')
     app['siriclient'] = SIRIClient(config["mot"]["url"],
                                    config["mot"]["user_id"])
     db.init_app(app)
     app.add_routes([
         web.get('/{stop_code:\d+}', self.handle_station),
         web.get('/{stop_code:\d+}/', self.handle_station),
         web.get('/operators', self.handle_operator_index),
         web.get('/operators/', self.handle_operator_index),
         web.get('/{operator:\w+}', self.handle_operator),
         web.get('/{operator:\w+}/', self.handle_operator),
         web.get('/rail/stations', self.handle_rail_stations),
         web.get('/rail/stations/', self.handle_rail_stations),
         web.get('/rail/map', self.handle_rail_map),
         web.get('/rail/map/', self.handle_rail_map),
         web.get('/operators/{operator}/{route_number}', self.handle_route),
         web.get('/operators/{operator}/{route_number}/{alternative}',
                 self.handle_route),
         web.get('/operators/{operator}', self.handle_operator),
         web.get('/{operator}/{route_number}', self.handle_route),
         web.get('/{operator}/{route_number}/{alternative}',
                 self.handle_route),
         web.get('/', self.handle_index)
     ])
     app.router.add_static(
         "/static/", os.path.join(os.path.dirname(__file__), '..',
                                  "static/"))
     self._app = app
Beispiel #59
0
# examples/server_simple.py
from aiohttp import web

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)
async def GET_establish_new_connection(request: web.Request):
    ws = web.WebSocketResponse()
    await ws.prepare(request)
    client_websockets.append(ws)

    async for msg in ws:
        print(f"Message received fom client: {msg.data}")
        await ws.send_str(f'Response of "{msg.data}"')

    print("Websocket connection closed")
    return ws


app = web.Application()
app.add_routes([
    web.get(r"/about", GET_about),
    web.patch(r"/sensor", PATCH_sensor),
    web.get(r"/sensor", GET_sensor),
    web.get(r"/sensor/live", GET_sensor_live),
    web.get("/sensor/events", GET_establish_new_connection),
])

hapic.set_context(
    AiohttpContext(app, default_error_builder=SerpycoDefaultErrorBuilder()))

hapic.add_documentation_view("/api/doc", "DOC", "Generated doc")
print(json.dumps(hapic.generate_doc()))
aiohttp_autoreload.start()
web.run_app(app)