本文整理汇总了Python中aiohttp.web.json_response方法的典型用法代码示例。如果您正苦于以下问题:Python web.json_response方法的具体用法?Python web.json_response怎么用?Python web.json_response使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类aiohttp.web
的用法示例。
在下文中一共展示了web.json_response方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: messages
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import json_response [as 别名]
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)
示例2: messages
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import json_response [as 别名]
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
示例3: messages
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import json_response [as 别名]
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)
示例4: info
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import json_response [as 别名]
def info(request):
"""HTTP Method to return node state to caller"""
log.request(request)
app = request.app
resp = StreamResponse()
resp.headers['Content-Type'] = 'application/json'
answer = {}
# copy relevant entries from state dictionary to response
answer['id'] = request.app['id']
answer['start_time'] = unixTimeToUTC(app['start_time'])
answer['last_health_check'] = unixTimeToUTC(app['last_health_check'])
answer['up_time'] = elapsedTime(app['start_time'])
answer['cluster_state'] = app['cluster_state']
answer['bucket_name'] = app['bucket_name']
answer['target_sn_count'] = await getTargetNodeCount(app, "sn")
answer['active_sn_count'] = getActiveNodeCount(app, "sn")
answer['target_dn_count'] = await getTargetNodeCount(app, "dn")
answer['active_dn_count'] = getActiveNodeCount(app, "dn")
resp = json_response(answer)
log.response(request, resp=resp)
return resp
示例5: GET_Domain
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import json_response [as 别名]
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
示例6: register
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import json_response [as 别名]
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)
示例7: login
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import json_response [as 别名]
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)
示例8: execute_query
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import json_response [as 别名]
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)
示例9: get_stream_apps
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import json_response [as 别名]
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)
示例10: refresh_ssh_keypair
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import json_response [as 别名]
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)
示例11: set_config
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import json_response [as 别名]
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'})
示例12: handle_graphql
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import json_response [as 别名]
def handle_graphql(request):
data = await request.json()
result = await request.app['graphql-endpoint'].dispatch(data)
return web.json_response(result)
示例13: nodestate
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import json_response [as 别名]
def nodestate(request):
"""HTTP method to return information about registed nodes"""
log.request(request)
node_type = request.match_info.get('nodetype', '*')
node_number = '*'
if node_type != '*':
node_number = request.match_info.get('nodenumber', '*')
log.info("nodestate/{}/{}".format(node_type, node_number))
if node_type not in ("sn", "dn", "*"):
msg="invalid node_type"
log.response(request, code=400, message=msg)
raise HTTPBadRequest(reason=msg)
app = request.app
resp = StreamResponse()
resp.headers['Content-Type'] = 'application/json'
if node_number == '*':
nodes = []
for node in app["nodes"]:
if node["node_type"] == node_type or node_type == "*":
nodes.append(node)
log.debug(f"Added a node in nodestate method, up to {len(nodes)} nodes.")
answer = {"nodes": nodes }
else:
answer = {}
for node in app["nodes"]:
if node["node_type"] == node_type and str(node["node_number"]) == node_number:
answer = node
break
answer["cluster_state"] = app["cluster_state"]
resp = json_response(answer)
log.response(request, resp=resp)
return resp
示例14: GET_Datatype
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import json_response [as 别名]
def GET_Datatype(request):
"""HTTP GET method to return JSON for /groups/
"""
log.request(request)
app = request.app
params = request.rel_url.query
ctype_id = get_obj_id(request)
if not isValidUuid(ctype_id, obj_class="type"):
log.error(f"Unexpected type_id: {ctype_id}")
raise HTTPInternalServerError()
if "bucket" in params:
bucket = params["bucket"]
else:
bucket = None
ctype_json = await get_metadata_obj(app, ctype_id, bucket=bucket)
resp_json = { }
resp_json["id"] = ctype_json["id"]
resp_json["root"] = ctype_json["root"]
resp_json["created"] = ctype_json["created"]
resp_json["lastModified"] = ctype_json["lastModified"]
resp_json["type"] = ctype_json["type"]
resp_json["attributeCount"] = len(ctype_json["attributes"])
if "include_attrs" in params and params["include_attrs"]:
resp_json["attributes"] = ctype_json["attributes"]
resp = json_response(resp_json)
log.response(request, resp=resp)
return resp
示例15: DELETE_Datatype
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import json_response [as 别名]
def DELETE_Datatype(request):
"""HTTP DELETE method for datatype
"""
log.request(request)
app = request.app
params = request.rel_url.query
ctype_id = get_obj_id(request)
log.info(f"DELETE ctype: {ctype_id}")
if "bucket" in params:
bucket = params["bucket"]
else:
bucket = None
# verify the id exist
obj_found = await check_metadata_obj(app, ctype_id)
if not obj_found:
log.warn(f"Delete on non-existent obj: {ctype_id}")
raise HTTPNotFound
log.info("deleting ctype: {}".format(ctype_id))
notify=True
if "Notify" in params and not params["Notify"]:
log.info("notify value: {}".format(params["Notify"]))
notify=False
log.info("notify: {}".format(notify))
await delete_metadata_obj(app, ctype_id, bucket=bucket, notify=notify)
resp_json = { }
resp = json_response(resp_json)
log.response(request, resp=resp)
return resp