本文整理汇总了Python中snf_django.lib.api.utils.get_json_body函数的典型用法代码示例。如果您正苦于以下问题:Python get_json_body函数的具体用法?Python get_json_body怎么用?Python get_json_body使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_json_body函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update_server_name
def update_server_name(request, server_id):
# Normal Response Code: 204
# Error Response Codes: computeFault (400, 500),
# serviceUnavailable (503),
# unauthorized (401),
# badRequest (400),
# badMediaType(415),
# itemNotFound (404),
# buildInProgress (409),
# overLimit (413)
credentials = request.credentials
req = utils.get_json_body(request)
log.debug("User: %s, VM: %s, Action: rename, Request: %s",
credentials.userid, server_id, req)
req = utils.get_attribute(req, "server", attr_type=dict, required=True)
name = utils.get_attribute(req, "name", attr_type=basestring,
required=True)
servers.rename(server_id, new_name=name, credentials=credentials)
log.info("User %s renamed server %s", credentials.userid, server_id)
return HttpResponse(status=204)
示例2: create_snapshot
def create_snapshot(request):
"""Create a new Snapshot."""
req = utils.get_json_body(request)
log.debug("create_snapshot %s", req)
user_id = request.user_uniq
snap_dict = utils.get_attribute(req, "snapshot", required=True,
attr_type=dict)
volume_id = utils.get_attribute(snap_dict, "volume_id", required=True)
volume = util.get_volume(user_id, volume_id, for_update=True,
non_deleted=True,
exception=faults.BadRequest)
metadata = utils.get_attribute(snap_dict, "metadata", required=False,
attr_type=dict, default={})
name = utils.get_attribute(snap_dict, "display_name", required=False,
attr_type=basestring,
default="Snapshot of volume '%s'" % volume_id)
description = utils.get_attribute(snap_dict, "display_description",
required=False,
attr_type=basestring, default="")
# TODO: What to do with force ?
force = utils.get_attribute(req, "force", required=False, attr_type=bool,
default=False)
snapshot = snapshots.create(user_id=user_id, volume=volume, name=name,
description=description, metadata=metadata,
force=force)
# Render response
data = json.dumps(dict(snapshot=snapshot_to_dict(snapshot, detail=False)))
return HttpResponse(data, status=202)
示例3: update_snapshot
def update_snapshot(request, snapshot_id):
credentials = request.credentials
util.assert_snapshots_enabled(request)
req = utils.get_json_body(request)
log.debug("User: %s, Snapshot: %s Action: update",
credentials.userid, snapshot_id)
snapshot = util.get_snapshot(credentials.userid, snapshot_id)
snap_dict = utils.get_attribute(req, "snapshot", attr_type=dict,
required=True)
new_name = utils.get_attribute(snap_dict, "display_name", required=False,
attr_type=basestring)
new_description = utils.get_attribute(snap_dict, "display_description",
required=False, attr_type=basestring)
if new_name is None and new_description is None:
raise faults.BadRequest("Nothing to update.")
snapshot = snapshots.update(snapshot, name=new_name,
description=new_description)
log.info("User %s updated snapshot %s", credentials.userid, snapshot["id"])
data = json.dumps({'snapshot': snapshot_to_dict(snapshot, detail=True)})
return HttpResponse(data, content_type="application/json", status=200)
示例4: update_metadata
def update_metadata(request, image_id):
# Normal Response Code: 201
# Error Response Codes: computeFault (400, 500),
# serviceUnavailable (503),
# unauthorized (401),
# badRequest (400),
# buildInProgress (409),
# badMediaType(415),
# overLimit (413)
req = utils.get_json_body(request)
log.info('update_image_metadata %s %s', image_id, req)
with backend.PlanktonBackend(request.credentials.userid) as b:
image = b.get_image(image_id)
try:
metadata = req['metadata']
assert isinstance(metadata, dict)
except (KeyError, AssertionError):
raise faults.BadRequest('Malformed request.')
properties = image['properties']
properties.update(metadata)
b.update_metadata(image_id, dict(properties=properties))
return util.render_metadata(request, properties, status=201)
示例5: serial_action
def serial_action(request, serial):
input_data = utils.get_json_body(request)
check_is_dict(input_data)
try:
serial = int(serial)
except ValueError:
raise BadRequest("Serial should be an integer.")
client_key = unicode(request.component_instance)
accept = 'accept' in input_data
reject = 'reject' in input_data
if accept == reject:
raise BadRequest('Specify either accept or reject action.')
result = qh.resolve_pending_commission(clientkey=client_key,
serial=serial,
accept=accept)
response = HttpResponse()
if not result:
response.status_code = 404
return response
示例6: allocate_floating_ip
def allocate_floating_ip(request):
"""Allocate a floating IP."""
req = utils.get_json_body(request)
floating_ip_dict = api.utils.get_attribute(req, "floatingip",
required=True, attr_type=dict)
userid = request.user_uniq
project = floating_ip_dict.get("project", None)
log.info('allocate_floating_ip user: %s request: %s', userid, req)
# the network_pool is a mandatory field
network_id = api.utils.get_attribute(floating_ip_dict,
"floating_network_id",
required=False,
attr_type=(basestring, int))
if network_id is None:
floating_ip = ips.create_floating_ip(userid, project=project)
else:
try:
network_id = int(network_id)
except ValueError:
raise faults.BadRequest("Invalid networkd ID.")
network = util.get_network(network_id, userid, for_update=True,
non_deleted=True)
address = api.utils.get_attribute(floating_ip_dict,
"floating_ip_address",
required=False,
attr_type=basestring)
floating_ip = ips.create_floating_ip(userid, network, address,
project=project)
log.info("User '%s' allocated floating IP '%s'", userid, floating_ip)
request.serialization = "json"
data = json.dumps({"floatingip": ip_to_dict(floating_ip)})
return HttpResponse(data, status=200)
示例7: update_server_name
def update_server_name(request, server_id):
# Normal Response Code: 204
# Error Response Codes: computeFault (400, 500),
# serviceUnavailable (503),
# unauthorized (401),
# badRequest (400),
# badMediaType(415),
# itemNotFound (404),
# buildInProgress (409),
# overLimit (413)
req = utils.get_json_body(request)
log.debug("User: %s, VM: %s, Action: rename, Request: %s",
request.user_uniq, server_id, req)
req = utils.get_attribute(req, "server", attr_type=dict, required=True)
name = utils.get_attribute(req, "name", attr_type=basestring,
required=True)
vm = util.get_vm(server_id, request.user_uniq, request.user_projects,
for_update=True, non_suspended=True, non_deleted=True)
servers.rename(vm, new_name=name)
log.info("User %s renamed server %s", request.user_uniq, vm.id)
return HttpResponse(status=204)
示例8: create_metadata_item
def create_metadata_item(request, image_id, key):
# Normal Response Code: 201
# Error Response Codes: computeFault (400, 500),
# serviceUnavailable (503),
# unauthorized (401),
# itemNotFound (404),
# badRequest (400),
# buildInProgress (409),
# badMediaType(415),
# overLimit (413)
req = utils.get_json_body(request)
log.info('create_image_metadata_item %s %s %s', image_id, key, req)
try:
metadict = req['meta']
assert isinstance(metadict, dict)
assert len(metadict) == 1
assert key in metadict
except (KeyError, AssertionError):
raise faults.BadRequest('Malformed request.')
val = metadict[key]
with backend.PlanktonBackend(request.credentials.userid) as b:
image = b.get_image(image_id)
properties = image['properties']
properties[key] = val
b.update_metadata(image_id, dict(properties=properties))
return util.render_meta(request, {key: val}, status=201)
示例9: resolve_pending_commissions
def resolve_pending_commissions(request):
input_data = utils.get_json_body(request)
check_is_dict(input_data)
client_key = unicode(request.component_instance)
accept = input_data.get('accept', [])
reject = input_data.get('reject', [])
if not isinstance(accept, list) or not isinstance(reject, list):
m = '"accept" and "reject" should reference lists of serials.'
raise BadRequest(m)
if not are_integer(accept) or not are_integer(reject):
raise BadRequest("Serials should be integer.")
result = qh.resolve_pending_commissions(clientkey=client_key,
accept_set=accept,
reject_set=reject)
accepted, rejected, notFound, conflicting = result
notFound = [(serial, notFoundCF(serial)) for serial in notFound]
conflicting = [(serial, conflictingCF(serial)) for serial in conflicting]
cloudfaults = notFound + conflicting
data = {'accepted': accepted,
'rejected': rejected,
'failed': cloudfaults
}
return json_response(data)
示例10: demux_server_action
def demux_server_action(request, server_id):
req = utils.get_json_body(request)
if not isinstance(req, dict) and len(req) != 1:
raise faults.BadRequest("Malformed request")
# Do not allow any action on deleted or suspended VMs
vm = util.get_vm(server_id, request.user_uniq, request.user_projects,
for_update=True, non_deleted=True, non_suspended=True)
try:
action = req.keys()[0]
except IndexError:
raise faults.BadRequest("Malformed Request.")
log.debug("User: %s, VM: %s, Action: %s Request: %s",
request.user_uniq, server_id, action, req)
if not isinstance(action, basestring):
raise faults.BadRequest("Malformed Request. Invalid action.")
if key_to_action(action) not in [x[0] for x in VirtualMachine.ACTIONS]:
if action not in ARBITRARY_ACTIONS:
raise faults.BadRequest("Action %s not supported" % action)
action_args = utils.get_attribute(req, action, required=True,
attr_type=dict)
return server_actions[action](request, vm, action_args)
示例11: membership_action
def membership_action(request, memb_id):
user = request.user
input_data = utils.get_json_body(request)
func, action_data = get_action(MEMBERSHIP_ACTION, input_data)
with ExceptionHandler():
func(memb_id, user, reason=action_data)
return HttpResponse()
示例12: update_volume
def update_volume(request, volume_id):
credentials = request.credentials
req = utils.get_json_body(request)
log.debug("User: %s, Volume: %s Action: update_volume, Request: %s",
credentials.userid, volume_id, req)
vol_req = utils.get_attribute(req, "volume", attr_type=dict,
required=True)
name = utils.get_attribute(vol_req, "display_name", required=False)
description = utils.get_attribute(vol_req, "display_description",
required=False)
delete_on_termination = utils.get_attribute(vol_req,
"delete_on_termination",
attr_type=bool,
required=False)
if name is None and description is None and\
delete_on_termination is None:
raise faults.BadRequest("Nothing to update.")
volume = volumes.update(volume_id, name, description,
delete_on_termination, credentials=credentials)
log.info("User %s updated volume %s", credentials.userid, volume_id)
data = json.dumps({'volume': volume_to_dict(volume, detail=True)})
return HttpResponse(data, content_type="application/json", status=200)
示例13: update_volume
def update_volume(request, volume_id):
req = utils.get_json_body(request)
log.debug('update_volume volume_id: %s, request: %s', volume_id, req)
volume = util.get_volume(request.user_uniq, volume_id, for_update=True,
non_deleted=True)
vol_req = utils.get_attribute(req, "volume", attr_type=dict,
required=True)
name = utils.get_attribute(vol_req, "display_name", required=False)
description = utils.get_attribute(vol_req, "display_description",
required=False)
delete_on_termination = utils.get_attribute(vol_req,
"delete_on_termination",
attr_type=bool,
required=False)
if name is None and description is None and\
delete_on_termination is None:
raise faults.BadRequest("Nothing to update.")
else:
volume = volumes.update(volume, name, description,
delete_on_termination)
data = json.dumps({'volume': volume_to_dict(volume, detail=True)})
return HttpResponse(data, content_type="application/json", status=200)
示例14: authenticate
def authenticate(request):
try:
content_length = get_content_length(request)
except faults.LengthRequired:
content_length = None
public_mode = True if not content_length else False
d = defaultdict(dict)
if not public_mode:
req = utils.get_json_body(request)
uuid = None
try:
token_id = req['auth']['token']['id']
except KeyError:
try:
token_id = req['auth']['passwordCredentials']['password']
uuid = req['auth']['passwordCredentials']['username']
except KeyError:
raise faults.BadRequest(
'Malformed request: missing credentials')
tenant = req['auth'].get('tenantName')
if token_id is None:
raise faults.BadRequest('Malformed request: missing token')
try:
user = AstakosUser.objects.get(auth_token=token_id)
except AstakosUser.DoesNotExist:
raise faults.Unauthorized('Invalid token')
validate_user(user)
if uuid is not None:
if user.uuid != uuid:
raise faults.Unauthorized('Invalid credentials')
if tenant:
if user.uuid != tenant:
raise faults.BadRequest('Not conforming tenantName')
d["access"]["token"] = {
"id": user.auth_token,
"expires": utils.isoformat(user.auth_token_expires),
"tenant": {"id": user.uuid, "name": user.realname}}
d["access"]["user"] = {
"id": user.uuid, 'name': user.realname,
"roles": [dict(id=str(g['id']), name=g['name']) for g in
user.groups.values('id', 'name')],
"roles_links": []}
d["access"]["serviceCatalog"] = get_endpoints()
if request.serialization == 'xml':
return xml_response({'d': d}, 'api/access.xml')
else:
return json_response(d)
示例15: create_server
def create_server(request):
# Normal Response Code: 202
# Error Response Codes: computeFault (400, 500),
# serviceUnavailable (503),
# unauthorized (401),
# badMediaType(415),
# itemNotFound (404),
# badRequest (400),
# serverCapacityUnavailable (503),
# overLimit (413)
req = utils.get_json_body(request)
user_id = request.user_uniq
log.info('create_server user: %s request: %s', user_id, req)
try:
server = req['server']
name = server['name']
metadata = server.get('metadata', {})
assert isinstance(metadata, dict)
image_id = server['imageRef']
flavor_id = server['flavorRef']
personality = server.get('personality', [])
assert isinstance(personality, list)
networks = server.get("networks")
if networks is not None:
assert isinstance(networks, list)
project = server.get("project")
except (KeyError, AssertionError):
raise faults.BadRequest("Malformed request")
volumes = None
dev_map = server.get("block_device_mapping_v2")
if dev_map is not None:
volumes = parse_block_device_mapping(dev_map)
# Verify that personalities are well-formed
util.verify_personality(personality)
# Get flavor (ensure it is active)
flavor = util.get_flavor(flavor_id, include_deleted=False)
if not flavor.allow_create:
msg = ("It is not allowed to create a server from flavor with id '%d',"
" see 'allow_create' flavor attribute")
raise faults.Forbidden(msg % flavor.id)
# Generate password
password = util.random_password()
vm = servers.create(user_id, name, password, flavor, image_id,
metadata=metadata, personality=personality,
project=project, networks=networks, volumes=volumes)
server = vm_to_dict(vm, detail=True)
server['status'] = 'BUILD'
server['adminPass'] = password
response = render_server(request, server, status=202)
return response