示例#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
示例#2
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)
示例#3
0
    def __init__(self, config):
        db = Gino(model_classes=tuple(gtfs_model.tables))
        app = web.Application(middlewares=[db])
        app["config"] = config

        db.init_app(app)
        app.add_routes([web.post('/{tail:.*}', self.handle_request)])
        self._app = app
示例#4
0
def test_post(router):
    async def handler(request):
        pass

    router.add_routes([web.post('/', handler)])

    route = list(router.routes())[0]
    assert route.handler is handler
    assert route.method == 'POST'
    assert str(route.url_for()) == '/'
示例#5
0
    def __init__(self, configuration):
        assert 'hookId' in configuration
        super().__init__(
            'project-releng',
            configuration['hookId'],
        )

        # Choose a mode between polling and webhook
        self.mode = configuration.get('mode', MODE_PHABRICATOR_POLLING)
        assert self.mode in (MODE_PHABRICATOR_POLLING, MODE_PHABRICATOR_WEBHOOK)
        logger.info('Running in mode', mode=self.mode)

        # Connect to Phabricator API
        assert 'phabricator_api' in configuration
        self.api = configuration['phabricator_api']

        # List enabled repositories
        enabled = configuration.get('repositories', ['mozilla-central', ])
        self.repos = {
            r['phid']: r
            for r in self.api.list_repositories()
            if r['fields']['name'] in enabled
        }
        assert len(self.repos) > 0, 'No repositories enabled'
        logger.info('Enabled Phabricator repositories', repos=[r['fields']['name'] for r in self.repos.values()])

        # Get actions to do on new diff
        self.actions = configuration.get('actions', [ACTION_TASKCLUSTER, ])
        logger.info('Enabled actions', actions=self.actions)

        # Start by getting top id
        diffs = self.api.search_diffs(limit=1)
        assert len(diffs) == 1
        self.latest_id = diffs[0]['id']

        # Add web route for new code review
        if self.mode == MODE_PHABRICATOR_WEBHOOK:
            self.routes.append(web.post('/codereview/new', self.new_code_review))

        # Load secure projects
        projects = self.api.search_projects(slugs=['secure-revision'])
        self.secure_projects = {
            p['phid']: p['fields']['name']
            for p in projects
        }
        logger.info('Loaded secure projects', projects=self.secure_projects.values())

        # Phabricator secure revision retries configuration
        self.phabricator_retries = configuration.get('phabricator_retries', 5)
        self.phabricator_sleep = configuration.get('phabricator_sleep', 10)
        assert isinstance(self.phabricator_retries, int)
        assert isinstance(self.phabricator_sleep, int)
        logger.info('Will retry Phabricator secure revision queries', retries=self.phabricator_retries, sleep=self.phabricator_sleep)  # noqa
示例#6
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)
    async def make_application(self) -> web.Application:
        """Get the aiohttp application instance."""

        middlewares = [validation_middleware]

        # admin-token and admin-token are mutually exclusive and required.
        # This should be enforced during parameter parsing but to be sure,
        # we check here.
        assert self.admin_insecure_mode ^ bool(self.admin_api_key)

        def is_unprotected_path(path: str):
            return path in [
                "/api/doc",
                "/api/docs/swagger.json",
                "/favicon.ico",
                "/ws",  # ws handler checks authentication
            ] or path.startswith("/static/swagger/")

        # If admin_api_key is None, then admin_insecure_mode must be set so
        # we can safely enable the admin server with no security
        if self.admin_api_key:

            @web.middleware
            async def check_token(request, handler):
                header_admin_api_key = request.headers.get("x-api-key")
                valid_key = self.admin_api_key == header_admin_api_key

                if valid_key or is_unprotected_path(request.path):
                    return await handler(request)
                else:
                    raise web.HTTPUnauthorized()

            middlewares.append(check_token)

        collector: Collector = await self.context.inject(Collector,
                                                         required=False)

        if self.task_queue:

            @web.middleware
            async def apply_limiter(request, handler):
                task = await self.task_queue.put(handler(request))
                return await task

            middlewares.append(apply_limiter)

        elif collector:

            @web.middleware
            async def collect_stats(request, handler):
                handler = collector.wrap_coro(handler, [handler.__qualname__])
                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, allow_head=False),
            web.get("/plugins", self.plugins_handler, allow_head=False),
            web.get("/status", self.status_handler, allow_head=False),
            web.post("/status/reset", self.status_reset_handler),
            web.get("/ws", self.websocket_handler, allow_head=False),
        ])

        plugin_registry: PluginRegistry = await self.context.inject(
            PluginRegistry, required=False)
        if plugin_registry:
            await plugin_registry.register_admin_routes(app)

        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)
        # get agent label
        agent_label = self.context.settings.get("default_label")
        version_string = f"v{__version__}"

        setup_aiohttp_apispec(app=app,
                              title=agent_label,
                              version=version_string,
                              swagger_path="/api/doc")
        app.on_startup.append(self.on_startup)
        return app
示例#8
0
    path = request.match_info.get("path")
    return {
        "path": path,
        "file_list": get_dir_info(dataset_dir + "/" + path),
    }


async def handle_post(request: web.Request) -> web.Response:
    reader = await request.multipart()
    while not reader.at_eof():
        field = await reader.next()
        if field.name == 'file':
            return await handle_file_upload(field)

    return web.Response(text="file not found")


app = web.Application()
app.add_routes([
    web.post('/upload', handle_post),
    web.get('/api/dataset', handle_api),
    web.get('/{path:.*}/preview.gif', handle_preview),
    web.get('/{path:.*}', handle_get),
])
app.on_startup.append(register)
aiohttp_jinja2.setup(app,
                     loader=jinja2.FileSystemLoader(
                         os.path.join(os.getcwd(), "templates")))
if __name__ == '__main__':
    web.run_app(app, port=8000)
示例#9
0
def create(specs: OpenApiSpec) -> List[web.RouteDef]:
    # TODO: consider the case in which server creates routes for both v0 and v1!!!
    # TODO: should this be taken from servers instead?
    BASEPATH = "/v" + specs.info.version.split(".")[0]

    log.debug("creating %s ", __name__)
    routes = []

    # TODO: routing will be done automatically using operation_id/tags, etc...
    #   routes = auto_routing(specs, handlers)

    # diagnostics --
    path, handle = "/", handlers.check_health
    operation_id = specs.paths[path].operations["get"].operation_id
    routes.append(web.get(BASEPATH + path, handle, name=operation_id))

    path, handle = "/check/{action}", handlers.check_action
    operation_id = specs.paths[path].operations["post"].operation_id
    routes.append(web.post(BASEPATH + path, handle, name=operation_id))

    path, handle = "/locations", handlers.get_storage_locations
    operation_id = specs.paths[path].operations["get"].operation_id
    routes.append(web.get(BASEPATH + path, handle, name=operation_id))

    path, handle = (
        "/locations/{location_id}/files/metadata",
        handlers.get_files_metadata,
    )
    operation_id = specs.paths[path].operations["get"].operation_id
    routes.append(web.get(BASEPATH + path, handle, name=operation_id))

    path, handle = "/locations/{location_id}/datasets", handlers.get_datasets_metadata
    operation_id = specs.paths[path].operations["get"].operation_id
    routes.append(web.get(BASEPATH + path, handle, name=operation_id))

    path, handle = (
        "/locations/{location_id}/files/{fileId}/metadata",
        handlers.get_file_metadata,
    )
    operation_id = specs.paths[path].operations["get"].operation_id
    routes.append(web.get(BASEPATH + path, handle, name=operation_id))

    path, handle = (
        "/locations/{location_id}/datasets/{dataset_id}/metadata",
        handlers.get_files_metadata_dataset,
    )
    operation_id = specs.paths[path].operations["get"].operation_id
    routes.append(web.get(BASEPATH + path, handle, name=operation_id))

    # TODO: Implements update
    # path, handle = '/{location_id}/files/{fileId}/metadata', handlers.update_file_metadata
    # operation_id = specs.paths[path].operations['patch'].operation_id
    # routes.append( web.patch(BASEPATH+path, handle, name=operation_id) )

    path, handle = "/locations/{location_id}/files/{fileId}", handlers.download_file
    operation_id = specs.paths[path].operations["get"].operation_id
    routes.append(web.get(BASEPATH + path, handle, name=operation_id))

    path, handle = "/locations/{location_id}/files/{fileId}", handlers.delete_file
    operation_id = specs.paths[path].operations["delete"].operation_id
    routes.append(web.delete(BASEPATH + path, handle, name=operation_id))

    path, handle = "/locations/{location_id}/files/{fileId}", handlers.upload_file
    operation_id = specs.paths[path].operations["put"].operation_id
    routes.append(web.put(BASEPATH + path, handle, name=operation_id))

    path, handle = "/simcore-s3/folders", handlers.create_folders_from_project
    operation_id = specs.paths[path].operations["post"].operation_id
    routes.append(web.post(BASEPATH + path, handle, name=operation_id))

    path, handle = "/simcore-s3/folders/{folder_id}", handlers.delete_folders_of_project
    operation_id = specs.paths[path].operations["delete"].operation_id
    routes.append(web.delete(BASEPATH + path, handle, name=operation_id))

    return routes
示例#10
0
 def __init__(self, port=2903):
     self.port = port
     self.app = web.Application(debug=True)
     self.app.add_routes([web.post('/api', self.api)])
     self.runner = None
     self.server = None
示例#11
0
    id = run[0]
    await conn.execute(runs.delete(runs.c.id == id))


async def emulate_ejudge(run_id: int, contest_id: int):
    non_terminal = [96, 98]
    terminal = [0, 99, 8, 14, 9, 1, 10, 7, 11, 2, 3, 4, 5, 6]
    await remove_run_from_rmatics(run_id, contest_id)
    await send_status_to_listener(run_id, contest_id, random.choice(non_terminal))
    await send_status_to_listener(run_id, contest_id, random.choice(terminal))


async def handle(request):
    data = await request.post()  # json.loads(await request.text())
    if 'SID' in data:
        contest_id = data['SID']
        run_id, contest_id = await get_run_id(contest_id)
        request.loop.create_task(emulate_ejudge(run_id, contest_id))
        return web.Response(text=json.dumps({'run_id': run_id}))
    else:
        contest_id = data['contest_id']
        text = f'SID="{contest_id}";'
        return web.Response(text=text)


if __name__ == '__main__':
    app = web.Application()
    app.add_routes([web.post('/', handle)])

    web.run_app(app, port=11111)
示例#12
0
def create(specs: openapi.Spec) -> List[web.RouteDef]:
    # TODO: consider the case in which server creates routes for both v0 and v1!!!
    # TODO: should this be taken from servers instead?
    BASEPATH = "/v" + specs.info.version.split(".")[0]

    log.debug("creating %s ", __name__)
    routes = []

    # TODO: routing will be done automatically using operation_id/tags, etc...

    # storage --
    path, handler = "/storage/locations", storage_handlers.get_storage_locations
    operation_id = specs.paths[path].operations["get"].operation_id
    routes.append(web.get(BASEPATH + path, handler, name=operation_id))

    path, handler = (
        "/storage/locations/{location_id}:sync",
        storage_handlers.synchronise_meta_data_table,
    )
    operation_id = specs.paths[path].operations["post"].operation_id
    routes.append(web.post(BASEPATH + path, handler, name=operation_id))

    path, handler = (
        "/storage/locations/{location_id}/datasets",
        storage_handlers.get_datasets_metadata,
    )
    operation_id = specs.paths[path].operations["get"].operation_id
    routes.append(web.get(BASEPATH + path, handler, name=operation_id))

    path, handle = (
        "/storage/locations/{location_id}/files/metadata",
        storage_handlers.get_files_metadata,
    )
    operation_id = specs.paths[path].operations["get"].operation_id
    routes.append(web.get(BASEPATH + path, handle, name=operation_id))

    path, handle = (
        "/storage/locations/{location_id}/datasets/{dataset_id}/metadata",
        storage_handlers.get_files_metadata_dataset,
    )
    operation_id = specs.paths[path].operations["get"].operation_id
    routes.append(web.get(BASEPATH + path, handle, name=operation_id))

    path, handle = (
        "/storage/locations/{location_id}/files/{fileId}/metadata",
        storage_handlers.get_file_metadata,
    )
    operation_id = specs.paths[path].operations["get"].operation_id
    routes.append(web.get(BASEPATH + path, handle, name=operation_id))

    # TODO: Implements update
    # path, handle = '/{location_id}/files/{fileId}/metadata', handlers.update_file_metadata
    # operation_id = specs.paths[path].operations['patch'].operation_id
    # routes.append( web.patch(BASEPATH+path, handle, name=operation_id) )

    path, handle = (
        "/storage/locations/{location_id}/files/{fileId}",
        storage_handlers.download_file,
    )
    operation_id = specs.paths[path].operations["get"].operation_id
    routes.append(web.get(BASEPATH + path, handle, name=operation_id))

    path, handle = (
        "/storage/locations/{location_id}/files/{fileId}",
        storage_handlers.delete_file,
    )
    operation_id = specs.paths[path].operations["delete"].operation_id
    routes.append(web.delete(BASEPATH + path, handle, name=operation_id))

    path, handle = (
        "/storage/locations/{location_id}/files/{fileId}",
        storage_handlers.upload_file,
    )
    operation_id = specs.paths[path].operations["put"].operation_id
    routes.append(web.put(BASEPATH + path, handle, name=operation_id))

    return routes
示例#13
0
    if request.method == 'POST':
        data = await request.post()
        key = data.get('key')
    elif request.method == 'GET':
        url_key = request.match_info['url_key']
        key = url_key.replace('+', ' ')
    else:
        web.Response(text='Error', status=404)

    text, links = await get_content(key)

    context = {
        'website': 'New doorway page',
        'keyword': key.title(),
        'links': links,
        'text': text
    }
    response = aiohttp_jinja2.render_template('page.html', request, context)
    return response


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

app.add_routes([web.static('/static', 'static')])
app.add_routes([web.get('/', index)])
app.add_routes([web.post('/', search)])
app.add_routes([web.get('/{url_key}', search)])

web.run_app(app, host='127.0.0.1', port=5000)
示例#14
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)])
示例#15
0
    token = kwargs["token"]
    client = async_hvac.AsyncClient(settings.VAULT_ADDR, token=token)
    try:
        return web.json_response(await client.lookup_token())
    except async_hvac.exceptions.Forbidden:
        raise web.HTTPNotFound()
    finally:
        await client.close()


@use_args({"token": fields.Str(required=True, location="match_info")})
async def show_secret_contents(request, kwargs):
    token = kwargs["token"]
    client = async_hvac.AsyncClient(settings.VAULT_ADDR, token=token)
    try:
        return web.json_response(await client.read(CUBBYHOLE_PATH))
    except async_hvac.exceptions.Forbidden:
        raise web.HTTPNotFound()
    finally:
        await client.close()


routes = [
    web.post("/new", handler=new_secret),
    web.get("/show/{token}", handler=show_secret, name="show_secret"),
    web.get("/show/{token}/contents", handler=show_secret_contents),
]

app = web.Application()
app.add_routes(routes)
示例#16
0
from aiocron import crontab
from services import load
from views import reload, search_codes, codes_countries, info_about_country

env_path = Path(".") / "example.env"
load_dotenv(dotenv_path=env_path)


@crontab("0 2 * * *", tz=pytz.timezone("Europe/Moscow"))
async def periodic():
    """
    Periodic start update data - 02:00 MSK
    :return:
    """
    await load(app)


app = web.Application()
app.on_startup.append(init_pg)
app.on_cleanup.append(close_pg)

app.add_routes([
    web.post("/reload", reload),
    web.post("/search_codes", search_codes),
    web.get("/codes_countries", codes_countries),
    web.get("/info_about_country", info_about_country),
])

if __name__ == "__main__":
    web.run_app(app)
示例#17
0
async def register(app: web.Application):
    """Register routes."""

    app.add_routes([web.post("/jsonld/sign", sign)])
    app.add_routes([web.post("/jsonld/verify", verify)])
示例#18
0

@aiohttp_jinja2.template('agents.html')
def get_agents(request):
    return dict(agents=agents.values())


async def shutdown(app):
    for ws in app['websockets'].values():
        await ws.close()
    app['websockets'].clear()


if __name__ == '__main__':
    templates_folder = Path(__file__).parent / 'templates'
    aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader(templates_folder))
    app.add_routes([
        web.get('/', index),
        web.post('/reset', reset),
        web.get('/messages', get_messages),
        web.post('/messages', add_messages),
        web.get('/ws', websocket_handler),
        web.post('/run', run_agent),
        web.get('/agents', get_agents),
    ])
    app['websockets'] = {}
    app.on_shutdown.append(shutdown)

    start_socket_server()
    web.run_app(app)
示例#19
0
        "「无可奉告」Android 版",
        "addr":
        f'tcp://{client.addr}:{client.port}',
        "terms_of_service":
        "http://wukefenggao.cn/code",
        "rpc_source_code":
        "https://github.com/skyzh/make-a-fortune/blob/master/tcp_proxy/__main__.py",
        "rpc_terms_of_service":
        "https://github.com/skyzh/make-a-fortune/blob/master/LICENSE"
    })


app = web.Application()
cors = aiohttp_cors.setup(app,
                          defaults={
                              "*":
                              aiohttp_cors.ResourceOptions(
                                  expose_headers="*",
                                  allow_headers="*",
                              ),
                          })

app.add_routes([web.post('/api/rpc_proxy', handle)])
app.add_routes([web.get('/api/version', version)])

for route in list(app.router.routes()):
    cors.add(route)

if __name__ == '__main__':
    web.run_app(app)
示例#20
0
def create_app(io_loop=asyncio.get_event_loop()):
    app: TypeApp = web.Application(middlewares=[])
    if DSN:
        from aiohttp_sentry import SentryMiddleware
        app.middlewares.append(
            SentryMiddleware({
                'environment': 'foo',
                'release': 'bar',
                'ignore_exceptions': [web.HTTPException],
                'dsn': DSN,
            }),
        )
    app.tz = pytz.timezone('Asia/Shanghai')
    app.on_cleanup.append(clean_up)
    app.client_session = aiohttp.ClientSession(loop=io_loop)
    setup_mongo(app, io_loop)

    aiohttp_session.setup(
        app,
        MongoStorage(
            collection=app.db.get_collection('user_session'),
            max_age=60 * 60 * 24 * 14,
        )
    )
    app.middlewares.append(session_middleware)
    aiohttp_jinja2.setup(
        app, loader=jinja2.FileSystemLoader(str(base_dir / 'templates'))
    )
    app.add_routes([
        web.get('/', redirect(github_url)),
        web.get('/auth', redirect(oauth_url)),
        web.get('/version', version),
        web.get('/oauth_callback', get_token),
        web.get('/api/v0.2/querySubjectID', query_subject_id),
        web.get('/statistics_missing_bangumi', statistics_missing_bangumi),
        web.get('/bilibili_missing_episode', missing_episode),
        web.get('/api/v0.1/collected_episode_info', collected_episode_info),
        web.post('/api/v0.1/refresh_token', refresh_auth_token),
        web.post('/api/v0.1/collect_episode_info', collect_episode_info),
        web.post('/api/v0.1/reportMissingBangumi', report_missing_bangumi),
        web.post('/api/v0.1/report_missing_episode', report_missing_episode),
        web.view('/api/v0.1/player_url', PlayerUrl),
    ])
    if os.getenv('DEV'):
        import json

        async def show_session(request: WebRequest):
            return web.json_response(
                {key: value for key, value in request.session.items()},
                dumps=lambda x: json.dumps(x, indent=2, ensure_ascii=False)
            )

        app.add_routes([
            web.get('/dev/show_session', show_session),
        ])
    cors = aiohttp_cors.setup(
        app,
        defaults={
            "*": aiohttp_cors.ResourceOptions(
                allow_credentials=True,
                expose_headers="*",
                allow_headers="*",
            )
        }
    )
    for route in list(app.router.routes()):
        cors.add(route)
    return app
示例#21
0
async def register(app: web.Application):
    """Register routes."""

    app.add_routes([
        web.get("/issue-credential/records",
                credential_exchange_list,
                allow_head=False),
        web.get(
            "/issue-credential/records/{cred_ex_id}",
            credential_exchange_retrieve,
            allow_head=False,
        ),
        web.post("/issue-credential/send", credential_exchange_send),
        web.post("/issue-credential/send-proposal",
                 credential_exchange_send_proposal),
        web.post("/issue-credential/send-offer",
                 credential_exchange_send_free_offer),
        web.post(
            "/issue-credential/records/{cred_ex_id}/send-offer",
            credential_exchange_send_bound_offer,
        ),
        web.post(
            "/issue-credential/records/{cred_ex_id}/send-request",
            credential_exchange_send_request,
        ),
        web.post(
            "/issue-credential/records/{cred_ex_id}/issue",
            credential_exchange_issue,
        ),
        web.post(
            "/issue-credential/records/{cred_ex_id}/store",
            credential_exchange_store,
        ),
        web.post("/issue-credential/revoke", credential_exchange_revoke),
        web.post(
            "/issue-credential/publish-revocations",
            credential_exchange_publish_revocations,
        ),
        web.post(
            "/issue-credential/records/{cred_ex_id}/remove",
            credential_exchange_remove,
        ),
        web.post(
            "/issue-credential/records/{cred_ex_id}/problem-report",
            credential_exchange_problem_report,
        ),
    ])
示例#22
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)
示例#23
0
    def _register_homeassistant(self) -> None:
        """Register Home Assistant functions."""
        api_hass = APIHomeAssistant()
        api_hass.coresys = self.coresys

        self.webapp.add_routes([
            web.get("/core/info", api_hass.info),
            web.get("/core/logs", api_hass.logs),
            web.get("/core/stats", api_hass.stats),
            web.post("/core/options", api_hass.options),
            web.post("/core/update", api_hass.update),
            web.post("/core/restart", api_hass.restart),
            web.post("/core/stop", api_hass.stop),
            web.post("/core/start", api_hass.start),
            web.post("/core/check", api_hass.check),
            web.post("/core/rebuild", api_hass.rebuild),
            # Remove with old Supervisor fallback
            web.get("/homeassistant/info", api_hass.info),
            web.get("/homeassistant/logs", api_hass.logs),
            web.get("/homeassistant/stats", api_hass.stats),
            web.post("/homeassistant/options", api_hass.options),
            web.post("/homeassistant/update", api_hass.update),
            web.post("/homeassistant/restart", api_hass.restart),
            web.post("/homeassistant/stop", api_hass.stop),
            web.post("/homeassistant/start", api_hass.start),
            web.post("/homeassistant/check", api_hass.check),
            web.post("/homeassistant/rebuild", api_hass.rebuild),
        ])
async def ensure_seeds_save():
    """
    Periodically save all seeds in file
    """
    global seeds_saver_running
    seeds_saver_running = True
    cycle_period = 60 * 5
    try:
        while True:
            await asyncio.sleep(cycle_period)
            dump(seeds_storage, open(files_path, 'w'))
    except:
        seeds_saver_running = False
        raise


if exists(files_path):
    # load from file if already exist
    seeds_storage = load(open(files_path, 'r'))

app = web.Application()
app.add_routes([
    web.post('/seed', set_seed),
    web.get('/get_test', get_test),
    web.post('/test_passed', test_passed),
    web.delete('/seed', delete_seed),
    web.get('/stat', stat)
]),
web.run_app(app, port=int(environ['PORT']))
示例#25
0
    def _register_addons(self) -> None:
        """Register Add-on functions."""
        api_addons = APIAddons()
        api_addons.coresys = self.coresys

        self.webapp.add_routes([
            web.get("/addons", api_addons.list),
            web.post("/addons/reload", api_addons.reload),
            web.get("/addons/{addon}/info", api_addons.info),
            web.post("/addons/{addon}/install", api_addons.install),
            web.post("/addons/{addon}/uninstall", api_addons.uninstall),
            web.post("/addons/{addon}/start", api_addons.start),
            web.post("/addons/{addon}/stop", api_addons.stop),
            web.post("/addons/{addon}/restart", api_addons.restart),
            web.post("/addons/{addon}/update", api_addons.update),
            web.post("/addons/{addon}/options", api_addons.options),
            web.post("/addons/{addon}/rebuild", api_addons.rebuild),
            web.get("/addons/{addon}/logs", api_addons.logs),
            web.get("/addons/{addon}/icon", api_addons.icon),
            web.get("/addons/{addon}/logo", api_addons.logo),
            web.get("/addons/{addon}/changelog", api_addons.changelog),
            web.get("/addons/{addon}/documentation", api_addons.documentation),
            web.post("/addons/{addon}/stdin", api_addons.stdin),
            web.post("/addons/{addon}/security", api_addons.security),
            web.get("/addons/{addon}/stats", api_addons.stats),
        ])
示例#26
0
 def add_post():
     routes.append(web.post(method.__getattribute__("path"),
                            method))
示例#27
0
def aiohttp_app(request_schema, request_callable_schema, loop, test_client,
                request):
    locations, nested = request.param

    @docs(
        tags=['mytag'],
        summary='Test method summary',
        description='Test method description',
    )
    @use_kwargs(request_schema, **locations)
    def handler_get(request):
        print(request.data)
        return web.json_response({'msg': 'done', 'data': {}})

    @use_kwargs(request_schema)
    def handler_post(request):
        print(request.data)
        return web.json_response({'msg': 'done', 'data': {}})

    @use_kwargs(request_callable_schema)
    def handler_post_callable_schema(request):
        print(request.data)
        return web.json_response({'msg': 'done', 'data': {}})

    @use_kwargs(request_schema)
    def handler_post_echo(request):
        return web.json_response(request['data'])

    @use_kwargs(request_schema, **locations)
    def handler_get_echo(request):
        print(request.data)
        return web.json_response(request['data'])

    class ViewClass(web.View):
        @docs(
            tags=['mytag'],
            summary='View method summary',
            description='View method description',
        )
        @use_kwargs(request_schema, **locations)
        async def get(self):
            return web.json_response(self.request['data'])

    @use_kwargs(request_schema, **locations)
    def handler_get_echo_old_data(request):
        print(request.data)
        return web.json_response(request.data)

    def other(request):
        return web.Response()

    app = web.Application()
    if nested:
        doc = AiohttpApiSpec(title='My Documentation',
                             version='v1',
                             url='/api/docs/api-docs')
        v1 = web.Application()
        v1.router.add_routes([
            web.get('/test', handler_get),
            web.post('/test', handler_post),
            web.post('/test_call', handler_post_callable_schema),
            web.get('/other', other),
            web.get('/echo', handler_get_echo),
            web.view('/class_echo', ViewClass),
            web.get('/echo_old', handler_get_echo_old_data),
            web.post('/echo', handler_post_echo),
        ])
        v1.middlewares.append(aiohttp_apispec_middleware)
        doc.register(v1)
        app.add_subapp('/v1/', v1)
    else:
        doc = AiohttpApiSpec(title='My Documentation',
                             version='v1',
                             url='/v1/api/docs/api-docs')
        app.router.add_routes([
            web.get('/v1/test', handler_get),
            web.post('/v1/test', handler_post),
            web.post('/v1/test_call', handler_post_callable_schema),
            web.get('/v1/other', other),
            web.get('/v1/echo', handler_get_echo),
            web.view('/v1/class_echo', ViewClass),
            web.get('/v1/echo_old', handler_get_echo_old_data),
            web.post('/v1/echo', handler_post_echo),
        ])
        app.middlewares.append(aiohttp_apispec_middleware)
        doc.register(app)

    return loop.run_until_complete(test_client(app))
示例#28
0
 def run(self, port):
     app = web.Application()
     app.add_routes([web.post('/', self.handle)])
     web.run_app(app, port=port)
示例#29
0
WEBAPP['agent'] = Agent()
WEBAPP['modules'] = {
    'connection': Connection(WEBAPP['agent']),
    'ui': Ui(WEBAPP['agent']),
    'admin_walletconnection': AdminWalletConnection(WEBAPP['agent'])
}
WEBAPP['agent'].modules = WEBAPP['modules']

UI_TOKEN = uuid.uuid4().hex
WEBAPP['agent'].ui_token = UI_TOKEN

ROUTES = [
    web.get('/', modules.ui.root),
    web.get('/ws', WEBAPP['ui_event_queue'].ws_handler),
    web.static('/res', 'view/res'),
    web.post('/indy', WEBAPP['msg_receiver'].handle_message),
    web.post('/offer', WEBAPP['conn_receiver'].handle_message)
]

WEBAPP.add_routes(ROUTES)

RUNNER = web.AppRunner(WEBAPP)
LOOP.run_until_complete(RUNNER.setup())

SERVER = web.TCPSite(runner=RUNNER, port=PORT)

if AGENTINITINCLI:
    try:
        LOOP.run_until_complete(WEBAPP['agent'].connect_wallet(
            WALLETNAME, WALLETPASS))
        print(
示例#30
0
 def _add_routes(self):
     self._web_app.add_routes([web.post('/', self._response_manipulator)])
示例#31
0
 async def http_server_start(self):
     self.session = aiohttp.ClientSession()
     self.app = web.Application()
     # add routes that we will need for this system with the corresponding coroutines
     self.app.add_routes([
         web.post('/PlayerMovement', self.player_move),
         web.post('/ClientJoin', self.client_join),
         web.post('/Ready', self.readied_up),
         web.post('/StartViewChange', self.start_view_change),
         web.post('/DoViewChange', self.do_view_change),
         web.post('/StartView', self.start_view),
         web.post('/Recover', self.recovery_help),
         web.post('/RecoveryResponse', self.recovery_response),
         web.post('/GetState', self.get_state),
         web.post('/Commit', self.apply_commit),
         web.post('/PlayerMoveOK', self.player_move_ok),
         web.get('/GetReplicaList', self.replica_list),
         web.post('/UpdateReplicaList', self.update_replicas),
         web.get('/ComputeGamestate', self.compute_gamestate),
         web.get('/Gamestate', self.receive_gamestate)
     ])
     self.runner = aiohttp.web.AppRunner(self.app)
     await self.runner.setup()
     self.site = web.TCPSite(self.runner, self.local_ip, 9999)
     await self.site.start()
示例#32
0
from aiohttp import web

from .player import handlers as player_handlers
from .playlistsmanager import handlers as pl_handlers
from .songsmanager import handlers as songs_manager

# Базовый маршрутизатор запросов
routes = [
    # Подключение к плееру
    web.get('/api/player/ws', player_handlers.ws_handler),
    # Урлы работы с файлами
    web.get('/api/files', songs_manager.get_files_info_handler), #Отдать список файлов и папок в директории
    web.get('/api/files/update', songs_manager.update_database_handler), #Обновить БД mpd
    web.post('/api/files/toplaylist', songs_manager.song_to_playlist_handler), #Добавить в плейлист
    web.post('api/files/toplaying', songs_manager.song_to_current_playlist_handler), #Добавить в текущий список воспроизведения
    web.post('api/files/play', songs_manager.play_song_handler), #Воспроизвести выбранный файл 
    # Урлы работы с плейлистами
    # web.get('/api/playlists/current', mm_handlers.get_current_playlist),
    # web.get('/api/playlists/current/play/{id}', mm_handlers.set_playing_track),
    # web.get('/api/playlists/current/remove/{id}', mm_handlers.rm_track)
]
示例#33
0
    if not e:
        return web.Response(text="Resource not found")
    e.prompt = d
    return web.Response(text="ok")


def registTask(site, loop):
    global vrc
    cors = []
    vrc = VRCollection.vrCollection(loop, host=HOST)
    cors.append(site.start())  # webサーバ
    return (cors)


app = web.Application()
# HTTPd用のルーティング設定
routes = [
    web.get   ("/", web_hello),
    web.get   ("/vr", web_getportlist),
    web.get   ("/vr/{port}", web_getdetail),
    web.put   ("/vr/{port}", web_createvr),
    web.put   ("/vr/{port}/scenario/{id}", web_putscenario),
    web.delete("/vr/{port}/scenario/{id}", web_delscenario),
    web.post  ("/vr/{port}/restart", web_restart),
    web.get   ("/vr/{port}/status", web_getstatus),

    web.get("/vr/{port}/create", web_createport),
    web.get("/port/{port}/set/{desc}", web_getsetportname),
]
# その追加
app.add_routes(routes)
async def register(app: web.Application):
    """Register routes."""
    app.add_routes([
        web.post("/out-of-band/create-invitation", invitation_create),
        web.post("/out-of-band/receive-invitation", invitation_receive),
    ])
示例#35
0
 def make_server_app(self):
     app = web.Application()
     app.add_routes([web.post(self._server_path, self.handle_request)])
     return app
示例#36
0
        auth_data['client_id'] = '{}@AMER.OAUTHAP'.format(event['client_id'])
        longReply = lambda_client.invoke(FunctionName='levatrade-td-principals', InvocationType='RequestResponse', Payload=json.dumps(auth_data))
        result = json.loads(longReply['Payload'].read().decode())

        print('levatrade_auth_td() completed successfully at', date)

# TEMP: implementation of socket handling, will soon move to seperate class
if __name__ == "__main__":
    socket_connected = False
    td_connecting = True

    sched = BackgroundScheduler(timezone="US/Eastern")

    sched.add_job(start, CronTrigger.from_crontab('0 2 * * MON', timezone="US/Eastern"), id='start')
    sched.add_job(stop, CronTrigger.from_crontab('0 22 * * FRI', timezone="US/Eastern"), id='stop')
    sched.add_job(create_5_min_candles, CronTrigger.from_crontab('*/5 4-22 * * MON-FRI', timezone="US/Eastern"), id='create_5_min_candles')
    sched.add_job(update, CronTrigger.from_crontab('*/1 4-22 * * *', timezone="US/Eastern"), id='update')
    sched.add_job(auth_td, CronTrigger.from_crontab('0 12 * * MON-FRI', timezone="US/Eastern"), id='auth_td')
    sched.add_job(reauth_td, CronTrigger.from_crontab('*/5 4-20 * * MON-FRI', timezone="US/Eastern"), id='reauth_td')

    sched.configure()
    sched.start()
    scheduler_started = True

    app = web.Application()

    # post
    app.add_routes([web.post("/action", handle_action)])
    app.add_routes([web.post("/stop", handle_stop)])

    web.run_app(app, port=5000)
示例#37
0
async def register(app: web.Application):
    """Register routes."""
    app.add_routes([web.post("/schemas", schemas_send_schema)])
    app.add_routes([web.get("/schemas/created", schemas_created)])
    app.add_routes([web.get("/schemas/{id}", schemas_get_schema)])
示例#38
0
		crawling_data = await request.json()
		
		#Run our functions
		output_json = Text_Transformation_controller(crawling_data,initilization_data['max_n_gram_size'])
		
		#Send metadata to Link Analysis
		r = requests.post(initilization_data['Link_Analysis_address'],json.dumps(output_json['metadata']))
		
		#Send data to Indexing
		r = requests.post(initilization_data['Indexing_address'],json.dumps(output_json))
		
		#Tell Crawling that this was a success
		response_obj = {"status": 200}
		logging.warn("{0} - Successfully finished processing request.".format(unique_task_id))
		return web.Response(text=json.dumps(response_obj), status=200)
		
	except Exception as e:		
		#Tell Crawling that this was a failure
		logging.error("{0} - An Exception occurred.\nREQUEST:\n{1}".format(unique_task_id,json.dumps(request, indent=4)), exc_info=True)
		response_obj = {"status": 500, "message": "Incorrect JSON Format: "}

		logging.warn("{0} - Finished processing request in error.".format(unique_task_id))
		return web.Response(text=json.dumps(response_obj), status=500)
		
app=web.Application()
app.add_routes([web.post('/',post)])
web.run_app(app)
		
#if __name__== "__main__":
#	post("""{"url": "https://www.google.com", "metadata": { "timestamp": "2018-3-12", "forward_address" : ""}, "content": "<!DOCTYPE html>\\n<html>\\n\\t<head>\\n\\t\\t<title>Service Worker Toolbox</title>\\n\\t\\t<h1>Header Text testing</h1>\\t</head>\\n\\t<body>\\n\\t\\t<!-- Images -->\\n\\t\\t<h6>Testing header</h6>\\n\\t\\t<img src=\\"/images/contact.svg\\" height=\\"80\\" width=\\"80\\" />1\\n\\t\\t<img src=\\"/images/info.svg\\" height=\\"80\\" width=\\"80\\" />2\\n\\t\\t<img src=\\"/images/cv.svg\\" height=\\"80\\" width=\\"80\\" />3\\n\\t\\t<a href = \\"www.google.com\\">link</a>\\n\\t\\t<script>sdfsdf sdf</script>\\n\\t</body>4\\n</html>"}""")
示例#39
0
            "Content-Type": "application/json; charset=utf-8",
        },
    )


async def onMarkDelete(request):
    request_data = await request.json()

    query = db_mapper.Mark.delete().where(
        db_mapper.Mark.id == request_data["mark_id"])
    query.execute()

    return web.Response(
        text=json.dumps(None),
        headers={
            "Access-Control-Allow-Origin": "*",
            "Content-Type": "plain/text; charset=utf-8",
        },
    )


app = web.Application()
app.add_routes([
    web.post("/mark/save", onMarkAdd),
    web.post("/mark/delete", onMarkDelete),
    web.get("/mark/list", onMarkListGet),
    web.static("/", SCRIPT_DIR),
])

if __name__ == "__main__":
    web.run_app(app)
示例#40
0
                        json.dumps(
                            rpcutils.generateRPCResultResponse(
                                reqParsed[rpcutils.ID], payload)))

            elif msg.type == aiohttp.WSMsgType.ERROR:
                raise rpcErrorHandler.InternalServerError(
                    'ws connection closed with exception %s' %
                    ws.websocket.exception())

    except rpcErrorHandler.Error as e:
        await ws.websocket.send_str(
            json.dumps(
                rpcutils.generateRPCResultResponse(
                    reqParsed[rpcutils.ID] if reqParsed is not None else
                    rpcutils.UNKNOWN_RPC_REQUEST_ID, e.jsonEncode())))

    SubcriptionsHandler.removeClient(ws)
    return ws


if __name__ == '__main__':
    print("Server started")
    app = WebApp()
    app.add_routes([web.post('/rpc', rpcServerHandler)])
    app.add_routes([web.get('/ws', websocketServerHandler)])

    for webSocket in wsutils.webSockets:
        webSocket()

    web.run_app(app, port=80)
示例#41
0
文件: webhook.py 项目: HackSoc/csbot
 def create_app(self, e):
     with e['webserver'].create_subapp(self.config_get('prefix')) as app:
         app.add_routes([web.post('/{service}/{url_secret}', self.request_handler)])