Python aiohttp.web.json_response() Examples

The following are 30 code examples of aiohttp.web.json_response(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module aiohttp.web , or try the search function .
Example #1
Source File: app.py    From botbuilder-python with MIT License 6 votes vote down vote up
def messages(req: Request) -> Response:
    # Main bot message handler.
    if "application/json" in req.headers["Content-Type"]:
        body = await req.json()
    else:
        return Response(status=415)

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

    try:
        response = await ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
        if response:
            return json_response(data=response.body, status=response.status)
        return Response(status=201)
    except Exception as exception:
        raise exception 
Example #2
Source File: client_auth.py    From maubot with GNU Affero General Public License v3.0 6 votes vote down vote up
def login(request: web.Request) -> web.Response:
    info, err = await read_client_auth_request(request)
    if err is not None:
        return err
    api, _, username, password, _ = info
    device_id = ''.join(random.choices(string.ascii_uppercase + string.digits, k=8))
    try:
        return web.json_response(await api.request(Method.POST, Path.login, content={
            "type": "m.login.password",
            "identifier": {
                "type": "m.id.user",
                "user": username,
            },
            "password": password,
            "device_id": f"maubot_{device_id}",
        }))
    except MatrixRequestError as e:
        return web.json_response({
            "errcode": e.errcode,
            "error": e.message,
        }, status=e.http_status) 
Example #3
Source File: client_auth.py    From maubot with GNU Affero General Public License v3.0 6 votes vote down vote up
def register(request: web.Request) -> web.Response:
    info, err = await read_client_auth_request(request)
    if err is not None:
        return err
    api, secret, username, password, user_type = info
    res = await api.request(Method.GET, Path.admin.register)
    nonce = res["nonce"]
    mac = generate_mac(secret, nonce, username, password, user_type=user_type)
    try:
        return web.json_response(await api.request(Method.POST, Path.admin.register, content={
            "nonce": nonce,
            "username": username,
            "password": password,
            "admin": False,
            "mac": mac,
            # Older versions of synapse will ignore this field if it is None
            "user_type": user_type,
        }))
    except MatrixRequestError as e:
        return web.json_response({
            "errcode": e.errcode,
            "error": e.message,
            "http_status": e.http_status,
        }, status=HTTPStatus.INTERNAL_SERVER_ERROR) 
Example #4
Source File: instance_database.py    From maubot with GNU Affero General Public License v3.0 6 votes vote down vote up
def execute_query(instance: PluginInstance, sql_query: Union[str, Query],
                  rows_as_dict: bool = False) -> web.Response:
    try:
        res: ResultProxy = instance.inst_db.execute(sql_query)
    except exc.IntegrityError as e:
        return resp.sql_integrity_error(e, sql_query)
    except exc.OperationalError as e:
        return resp.sql_operational_error(e, sql_query)
    data = {
        "ok": True,
        "query": str(sql_query),
    }
    if res.returns_rows:
        row: RowProxy
        data["rows"] = [({key: check_type(value) for key, value in row.items()}
                         if rows_as_dict
                         else [check_type(value) for value in row])
                        for row in res]
        data["columns"] = res.keys()
    else:
        data["rowcount"] = res.rowcount
    if res.is_insert:
        data["inserted_primary_key"] = res.inserted_primary_key
    return web.json_response(data) 
Example #5
Source File: stream.py    From backend.ai-manager with GNU Lesser General Public License v3.0 6 votes vote down vote up
def get_stream_apps(request: web.Request) -> web.Response:
    session_name = request.match_info['session_name']
    access_key = request['keypair']['access_key']
    compute_session = await request.app['registry'].get_session(session_name, access_key)
    if compute_session['service_ports'] is None:
        return web.json_response([])
    resp = []
    for item in compute_session['service_ports']:
        response_dict = {
            'name': item['name'],
            'protocol': item['protocol'],
            'ports': item['container_ports'],
        }
        if 'url_template' in item.keys():
            response_dict['url_template'] = item['url_template']
        if 'allowed_arguments' in item.keys():
            response_dict['allowed_arguments'] = item['allowed_arguments']
        if 'allowed_envs' in item.keys():
            response_dict['allowed_envs'] = item['allowed_envs']
        resp.append(response_dict)
    return web.json_response(resp) 
Example #6
Source File: auth.py    From backend.ai-manager with GNU Lesser General Public License v3.0 6 votes vote down vote up
def refresh_ssh_keypair(request: web.Request) -> web.Response:
    domain_name = request['user']['domain_name']
    access_key = request['keypair']['access_key']
    log_fmt = 'AUTH.REFRESH_SSH_KEYPAIR(d:{}, ak:{})'
    log_args = (domain_name, access_key)
    log.info(log_fmt, *log_args)
    dbpool = request.app['dbpool']
    async with dbpool.acquire() as conn:
        pubkey, privkey = generate_ssh_keypair()
        data = {
            'ssh_public_key': pubkey,
            'ssh_private_key': privkey,
        }
        query = (keypairs.update()
                         .values(data)
                         .where(keypairs.c.access_key == access_key))
        await conn.execute(query)
    return web.json_response(data, status=200) 
Example #7
Source File: domain_dn.py    From hsds with Apache License 2.0 6 votes vote down vote up
def GET_Domain(request):
    """HTTP GET method to return JSON for /domains/
    """
    log.request(request)
    app = request.app

    domain = get_domain(request)
    log.debug(f"get domain: {domain}")
    bucket = getBucketForDomain(domain)
    if not bucket:
        log.error(f"expected bucket to be used in domain: {domain}")
        raise HTTPInternalServerError()
    log.debug(f"using bucket: {bucket}")
    domain_json = await get_metadata_obj(app, domain)
    log.debug(f"returning domain_json: {domain_json}")

    resp = json_response(domain_json)
    log.response(request, resp=resp)
    return resp 
Example #8
Source File: etcd.py    From backend.ai-manager with GNU Lesser General Public License v3.0 6 votes vote down vote up
def set_config(request: web.Request, params: Any) -> web.Response:
    etcd = request.app['config_server'].etcd
    log.info('ETCD.SET_CONFIG (ak:{}, key:{}, val:{})',
             request['keypair']['access_key'], params['key'], params['value'])
    if isinstance(params['value'], Mapping):
        updates = {}

        def flatten(prefix, o):
            for k, v in o.items():
                inner_prefix = prefix if k == '' else f'{prefix}/{k}'
                if isinstance(v, Mapping):
                    flatten(inner_prefix, v)
                else:
                    updates[inner_prefix] = v

        flatten(params['key'], params['value'])
        # TODO: chunk support if there are too many keys
        if len(updates) > 16:
            raise InvalidAPIParameters(
                'Too large update! Split into smaller key-value pair sets.')
        await etcd.put_dict(updates)
    else:
        await etcd.put(params['key'], params['value'])
    return web.json_response({'result': 'ok'}) 
Example #9
Source File: app.py    From botbuilder-python with MIT License 6 votes vote down vote up
def messages(req: Request) -> Response:
    # Main bot message handler.
    if "application/json" in req.headers["Content-Type"]:
        body = await req.json()
    else:
        return Response(status=415)

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

    try:
        invoke_response = await ADAPTER.process_activity(
            activity, auth_header, BOT.on_turn
        )
        if invoke_response:
            return json_response(
                data=invoke_response.body, status=invoke_response.status
            )
        return Response(status=201)
    except PermissionError:
        return Response(status=401)
    except Exception:
        return Response(status=500) 
Example #10
Source File: app.py    From botbuilder-python with MIT License 6 votes vote down vote up
def messages(req: Request) -> Response:
    # Main bot message handler.
    if "application/json" in req.headers["Content-Type"]:
        body = await req.json()
    else:
        return Response(status=415)

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

    try:
        invoke_response = await ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
        if invoke_response:
            return json_response(data=invoke_response.body, status=invoke_response.status)
        return Response(status=201)
    except PermissionError:
        return Response(status=401)
    except Exception:
        return Response(status=500) 
Example #11
Source File: app.py    From botbuilder-python with MIT License 6 votes vote down vote up
def messages(req: Request) -> Response:
    # Main bot message handler.
    if "application/json" in req.headers["Content-Type"]:
        body = await req.json()
    else:
        return Response(status=415)

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

    try:
        invoke_response = await ADAPTER.process_activity(
            activity, auth_header, BOT.on_turn
        )
        if invoke_response:
            return json_response(
                data=invoke_response.body, status=invoke_response.status
            )
        return Response(status=201)
    except PermissionError:
        return Response(status=401)
    except Exception:
        return Response(status=500) 
Example #12
Source File: app.py    From botbuilder-python with MIT License 6 votes vote down vote up
def messages(req: Request) -> Response:
    # Main bot message handler.
    if "application/json" in req.headers["Content-Type"]:
        body = await req.json()
    else:
        return Response(status=415)

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

    try:
        response = await ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
        if response:
            return json_response(data=response.body, status=response.status)
        return Response(status=201)
    except Exception as exception:
        raise exception 
Example #13
Source File: responses.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def plugin_import_error(error: str, stacktrace: str) -> web.Response:
        return web.json_response({
            "error": error,
            "stacktrace": stacktrace,
            "errcode": "plugin_invalid",
        }, status=HTTPStatus.BAD_REQUEST) 
Example #14
Source File: etcd.py    From backend.ai-manager with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_docker_registries(request) -> web.Response:
    '''
    Returns the list of all registered docker registries.
    '''
    log.info('ETCD.GET_DOCKER_REGISTRIES ()')
    etcd = request.app['registry'].config_server.etcd
    _registries = await get_known_registries(etcd)
    # ``yarl.URL`` is not JSON-serializable, so we need to represent it as string.
    known_registries: Mapping[str, str] = {k: v.human_repr() for k, v in _registries.items()}
    return web.json_response(known_registries, status=200) 
Example #15
Source File: etcd.py    From backend.ai-manager with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_resource_slots(request) -> web.Response:
    log.info('ETCD.GET_RESOURCE_SLOTS ()')
    known_slots = await request.app['config_server'].get_resource_slots()
    return web.json_response(known_slots, status=200) 
Example #16
Source File: responses.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def not_implemented(self) -> web.Response:
        return web.json_response({
            "error": "Not implemented",
            "errcode": "not_implemented",
        }, status=HTTPStatus.NOT_IMPLEMENTED) 
Example #17
Source File: responses.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def unsupported_plugin_loader(self) -> web.Response:
        return web.json_response({
            "error": "Existing plugin with same ID uses unsupported plugin loader",
            "errcode": "unsupported_plugin_loader",
        }, status=HTTPStatus.BAD_REQUEST) 
Example #18
Source File: responses.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def primary_user_not_found(self) -> web.Response:
        return web.json_response({
            "error": "Client for given primary user not found",
            "errcode": "primary_user_not_found",
        }, status=HTTPStatus.NOT_FOUND) 
Example #19
Source File: responses.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def internal_server_error(self) -> web.Response:
        return web.json_response({
            "error": "Internal server error",
            "errcode": "internal_server_error",
        }, status=HTTPStatus.INTERNAL_SERVER_ERROR) 
Example #20
Source File: responses.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def plugin_reload_error(error: str, stacktrace: str) -> web.Response:
        return web.json_response({
            "error": error,
            "stacktrace": stacktrace,
            "errcode": "plugin_reload_fail",
        }, status=HTTPStatus.INTERNAL_SERVER_ERROR) 
Example #21
Source File: responses.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def plugin_type_not_found(self) -> web.Response:
        return web.json_response({
            "error": "Given plugin type not found",
            "errcode": "plugin_type_not_found",
        }, status=HTTPStatus.NOT_FOUND) 
Example #22
Source File: responses.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def client_in_use(self) -> web.Response:
        return web.json_response({
            "error": "Plugin instances with this client as their primary user still exist",
            "errcode": "client_in_use",
        }, status=HTTPStatus.PRECONDITION_FAILED) 
Example #23
Source File: responses.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def plugin_in_use(self) -> web.Response:
        return web.json_response({
            "error": "Plugin instances of this type still exist",
            "errcode": "plugin_in_use",
        }, status=HTTPStatus.PRECONDITION_FAILED) 
Example #24
Source File: responses.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def user_exists(self) -> web.Response:
        return web.json_response({
            "error": "There is already a client with the user ID of that token",
            "errcode": "user_exists",
        }, status=HTTPStatus.CONFLICT) 
Example #25
Source File: vfolder.py    From backend.ai-manager with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_info(request: web.Request, row: VFolderRow) -> web.Response:
    resp: Dict[str, Any] = {}
    folder_name = request.match_info['name']
    access_key = request['keypair']['access_key']
    log.info('VFOLDER.GETINFO (ak:{}, vf:{})', access_key, folder_name)
    if row['permission'] is None:
        is_owner = True
        permission = VFolderPermission.OWNER_PERM
    else:
        is_owner = row['is_owner']
        permission = row['permission']
    # TODO: handle nested directory structure
    folder_path = get_folder_hostpath(row, request.app)
    loop = current_loop()
    num_files = await loop.run_in_executor(None, lambda: len(list(folder_path.iterdir())))
    resp = {
        'name': row['name'],
        'id': row['id'].hex,
        'host': row['host'],
        'numFiles': num_files,  # legacy
        'num_files': num_files,
        'created': str(row['created_at']),  # legacy
        'created_at': str(row['created_at']),
        'last_used': str(row['created_at']),
        'user': str(row['user']),
        'group': str(row['group']),
        'type': 'user' if row['user'] is not None else 'group',
        'is_owner': is_owner,
        'permission': permission,
    }
    return web.json_response(resp, status=200) 
Example #26
Source File: responses.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def method_not_allowed(self) -> web.Response:
        return web.json_response({
            "error": "Method not allowed",
            "errcode": "method_not_allowed",
        }, status=HTTPStatus.METHOD_NOT_ALLOWED) 
Example #27
Source File: responses.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def table_not_found(self) -> web.Response:
        return web.json_response({
            "error": "Given table not found in plugin database",
            "errcode": "table_not_found",
        }) 
Example #28
Source File: responses.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def plugin_has_no_database(self) -> web.Response:
        return web.json_response({
            "error": "Given plugin does not have a database",
            "errcode": "plugin_has_no_database",
        }) 
Example #29
Source File: responses.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def server_not_found(self) -> web.Response:
        return web.json_response({
            "error": "Registration target server not found",
            "errcode": "server_not_found",
        }, status=HTTPStatus.NOT_FOUND) 
Example #30
Source File: responses.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def instance_not_found(self) -> web.Response:
        return web.json_response({
            "error": "Plugin instance not found",
            "errcode": "instance_not_found",
        }, status=HTTPStatus.NOT_FOUND)