本文整理汇总了Python中nova.api.openstack.placement.util.extract_json函数的典型用法代码示例。如果您正苦于以下问题:Python extract_json函数的具体用法?Python extract_json怎么用?Python extract_json使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了extract_json函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update_resource_class
def update_resource_class(req):
"""PUT to create or validate the existence of single resource class.
On a successful create return 201. Return 204 if the class already
exists. If the resource class is not a custom resource class, return
a 400. 409 might be a better choice, but 400 aligns with previous code.
"""
name = util.wsgi_path_item(req.environ, 'name')
context = req.environ['placement.context']
# Use JSON validation to validation resource class name.
util.extract_json('{"name": "%s"}' % name, PUT_RC_SCHEMA_V1_2)
status = 204
try:
rc = objects.ResourceClass.get_by_name(context, name)
except exception.NotFound:
try:
rc = objects.ResourceClass(context, name=name)
rc.create()
status = 201
# We will not see ResourceClassCannotUpdateStandard because
# that was already caught when validating the {name}.
except exception.ResourceClassExists:
# Someone just now created the class, so stick with 204
pass
req.response.status = status
req.response.content_type = None
req.response.location = util.resource_class_url(req.environ, rc)
return req.response
示例2: create_resource_provider
def create_resource_provider(req):
"""POST to create a resource provider.
On success return a 201 response with an empty body and a location
header pointing to the newly created resource provider.
"""
context = req.environ['placement.context']
data = util.extract_json(req.body, POST_RESOURCE_PROVIDER_SCHEMA)
try:
uuid = data.get('uuid', uuidutils.generate_uuid())
resource_provider = objects.ResourceProvider(
context, name=data['name'], uuid=uuid)
resource_provider.create()
except db_exc.DBDuplicateEntry as exc:
raise webob.exc.HTTPConflict(
_('Conflicting resource provider already exists: %(error)s') %
{'error': exc},
json_formatter=util.json_error_formatter)
except exception.ObjectActionError as exc:
raise webob.exc.HTTPBadRequest(
_('Unable to create resource provider %(rp_uuid)s: %(error)s') %
{'rp_uuid': uuid, 'error': exc},
json_formatter=util.json_error_formatter)
req.response.location = util.resource_provider_url(
req.environ, resource_provider)
req.response.status = 201
req.response.content_type = None
return req.response
示例3: set_aggregates
def set_aggregates(req):
context = req.environ['placement.context']
context.can(policies.UPDATE)
want_version = req.environ[microversion.MICROVERSION_ENVIRON]
consider_generation = want_version.matches(
min_version=_INCLUDE_GENERATION_VERSION)
put_schema = schema.PUT_AGGREGATES_SCHEMA_V1_1
if consider_generation:
put_schema = schema.PUT_AGGREGATES_SCHEMA_V1_19
uuid = util.wsgi_path_item(req.environ, 'uuid')
resource_provider = rp_obj.ResourceProvider.get_by_uuid(
context, uuid)
data = util.extract_json(req.body, put_schema)
if consider_generation:
# Check for generation conflict
rp_gen = data['resource_provider_generation']
if resource_provider.generation != rp_gen:
raise webob.exc.HTTPConflict(
_("Resource provider's generation already changed. Please "
"update the generation and try again."),
comment=errors.CONCURRENT_UPDATE)
aggregate_uuids = data['aggregates']
else:
aggregate_uuids = data
_set_aggregates(resource_provider, aggregate_uuids,
increment_generation=consider_generation)
return _send_aggregates(req, resource_provider, aggregate_uuids)
示例4: update_resource_class
def update_resource_class(req):
"""PUT to update a single resource class.
On success return a 200 response with a representation of the updated
resource class.
"""
name = util.wsgi_path_item(req.environ, 'name')
context = req.environ['placement.context']
data = util.extract_json(req.body, PUT_RC_SCHEMA_V1_2)
# The containing application will catch a not found here.
rc = objects.ResourceClass.get_by_name(context, name)
rc.name = data['name']
try:
rc.save()
except exception.ResourceClassExists:
raise webob.exc.HTTPConflict(
_('Resource class already exists: %(name)s') %
{'name': name},
json_formatter=util.json_error_formatter)
except exception.ResourceClassCannotUpdateStandard:
raise webob.exc.HTTPBadRequest(
_('Cannot update standard resource class %(rp_name)s') %
{'rp_name': name},
json_formatter=util.json_error_formatter)
req.response.body = jsonutils.dumps(
_serialize_resource_class(req.environ, rc)
)
req.response.status = 200
req.response.content_type = 'application/json'
return req.response
示例5: create_resource_class
def create_resource_class(req):
"""POST to create a resource class.
On success return a 201 response with an empty body and a location
header pointing to the newly created resource class.
"""
context = req.environ['placement.context']
data = util.extract_json(req.body, POST_RC_SCHEMA_V1_2)
try:
rc = objects.ResourceClass(context, name=data['name'])
rc.create()
except exception.ResourceClassExists:
raise webob.exc.HTTPConflict(
_('Conflicting resource class already exists: %(name)s') %
{'name': data['name']})
except exception.MaxDBRetriesExceeded:
raise webob.exc.HTTPConflict(
_('Max retries of DB transaction exceeded attempting '
'to create resource class: %(name)s, please'
'try again.') %
{'name': data['name']})
req.response.location = util.resource_class_url(req.environ, rc)
req.response.status = 201
req.response.content_type = None
return req.response
示例6: test_valid
def test_valid(self):
data = util.extract_json(
'{"name": "cow", '
'"uuid": "%s"}' % uuidsentinel.rp_uuid,
self.schema)
self.assertEqual('cow', data['name'])
self.assertEqual(uuidsentinel.rp_uuid, data['uuid'])
示例7: create_resource_provider
def create_resource_provider(req):
"""POST to create a resource provider.
On success return a 201 response with an empty body and a location
header pointing to the newly created resource provider.
"""
context = req.environ['placement.context']
data = util.extract_json(req.body, POST_RESOURCE_PROVIDER_SCHEMA)
try:
uuid = data.get('uuid', uuidutils.generate_uuid())
resource_provider = objects.ResourceProvider(
context, name=data['name'], uuid=uuid)
resource_provider.create()
except db_exc.DBDuplicateEntry as exc:
# Whether exc.columns has one or two entries (in the event
# of both fields being duplicates) appears to be database
# dependent, so going with the complete solution here.
duplicate = ', '.join(['%s: %s' % (column, data[column])
for column in exc.columns])
raise webob.exc.HTTPConflict(
_('Conflicting resource provider %(duplicate)s already exists.') %
{'duplicate': duplicate})
except exception.ObjectActionError as exc:
raise webob.exc.HTTPBadRequest(
_('Unable to create resource provider %(rp_uuid)s: %(error)s') %
{'rp_uuid': uuid, 'error': exc})
req.response.location = util.resource_provider_url(
req.environ, resource_provider)
req.response.status = 201
req.response.content_type = None
return req.response
示例8: update_resource_provider
def update_resource_provider(req):
"""PUT to update a single resource provider.
On success return a 200 response with a representation of the updated
resource provider.
"""
uuid = util.wsgi_path_item(req.environ, 'uuid')
context = req.environ['placement.context']
# The containing application will catch a not found here.
resource_provider = objects.ResourceProvider.get_by_uuid(
context, uuid)
data = util.extract_json(req.body, PUT_RESOURCE_PROVIDER_SCHEMA)
resource_provider.name = data['name']
try:
resource_provider.save()
except db_exc.DBDuplicateEntry as exc:
raise webob.exc.HTTPConflict(
_('Conflicting resource provider already exists: %(error)s') %
{'error': exc},
json_formatter=util.json_error_formatter)
except exception.ObjectActionError as exc:
raise webob.exc.HTTPBadRequest(
_('Unable to save resource provider %(rp_uuid)s: %(error)s') %
{'rp_uuid': uuid, 'error': exc},
json_formatter=util.json_error_formatter)
req.response.body = jsonutils.dumps(
_serialize_provider(req.environ, resource_provider))
req.response.status = 200
req.response.content_type = 'application/json'
return req.response
示例9: update_traits_for_resource_provider
def update_traits_for_resource_provider(req):
context = req.environ['placement.context']
uuid = util.wsgi_path_item(req.environ, 'uuid')
data = util.extract_json(req.body, SET_TRAITS_FOR_RP_SCHEMA)
rp_gen = data['resource_provider_generation']
traits = data['traits']
resource_provider = objects.ResourceProvider.get_by_uuid(
context, uuid)
if resource_provider.generation != rp_gen:
raise webob.exc.HTTPConflict(
_("Resource provider's generation already changed. Please update "
"the generation and try again."),
json_formatter=util.json_error_formatter)
trait_objs = objects.TraitList.get_all(
context, filters={'name_in': traits})
traits_name = set([obj.name for obj in trait_objs])
non_existed_trait = set(traits) - set(traits_name)
if non_existed_trait:
raise webob.exc.HTTPBadRequest(
_("No such trait %s") % ', '.join(non_existed_trait))
resource_provider.set_traits(trait_objs)
response_body = _serialize_traits(trait_objs)
response_body[
'resource_provider_generation'] = resource_provider.generation
req.response.status = 200
req.response.body = encodeutils.to_utf8(jsonutils.dumps(response_body))
req.response.content_type = 'application/json'
return req.response
示例10: _set_allocations
def _set_allocations(req, schema):
context = req.environ['placement.context']
consumer_uuid = util.wsgi_path_item(req.environ, 'consumer_uuid')
data = util.extract_json(req.body, schema)
allocation_data = data['allocations']
# If the body includes an allocation for a resource provider
# that does not exist, raise a 400.
allocation_objects = []
for allocation in allocation_data:
resource_provider_uuid = allocation['resource_provider']['uuid']
try:
resource_provider = objects.ResourceProvider.get_by_uuid(
context, resource_provider_uuid)
except exception.NotFound:
raise webob.exc.HTTPBadRequest(
_("Allocation for resource provider '%(rp_uuid)s' "
"that does not exist.") %
{'rp_uuid': resource_provider_uuid})
resources = allocation['resources']
for resource_class in resources:
allocation = objects.Allocation(
resource_provider=resource_provider,
consumer_id=consumer_uuid,
resource_class=resource_class,
used=resources[resource_class])
allocation_objects.append(allocation)
allocations = objects.AllocationList(
context,
objects=allocation_objects,
project_id=data.get('project_id'),
user_id=data.get('user_id'),
)
try:
allocations.create_all()
LOG.debug("Successfully wrote allocations %s", allocations)
# InvalidInventory is a parent for several exceptions that
# indicate either that Inventory is not present, or that
# capacity limits have been exceeded.
except exception.NotFound as exc:
raise webob.exc.HTTPBadRequest(
_("Unable to allocate inventory for resource provider "
"%(rp_uuid)s: %(error)s") %
{'rp_uuid': resource_provider_uuid, 'error': exc})
except exception.InvalidInventory as exc:
raise webob.exc.HTTPConflict(
_('Unable to allocate inventory: %(error)s') % {'error': exc})
except exception.ConcurrentUpdateDetected as exc:
raise webob.exc.HTTPConflict(
_('Inventory changed while attempting to allocate: %(error)s') %
{'error': exc})
req.response.status = 204
req.response.content_type = None
return req.response
示例11: _extract_inventory
def _extract_inventory(body, schema):
"""Extract and validate inventory from JSON body."""
data = util.extract_json(body, schema)
inventory_data = copy.copy(INVENTORY_DEFAULTS)
inventory_data.update(data)
return inventory_data
示例12: create_resource_provider
def create_resource_provider(req):
"""POST to create a resource provider.
On success return a 201 response with an empty body
(microversions 1.0 - 1.19) or a 200 response with a
payload representing the newly created resource provider
(microversions 1.20 - latest), and a location header
pointing to the resource provider.
"""
context = req.environ['placement.context']
context.can(policies.CREATE)
schema = rp_schema.POST_RESOURCE_PROVIDER_SCHEMA
want_version = req.environ[microversion.MICROVERSION_ENVIRON]
if want_version.matches((1, 14)):
schema = rp_schema.POST_RP_SCHEMA_V1_14
data = util.extract_json(req.body, schema)
try:
if data.get('uuid'):
# Normalize UUID with no proper dashes into dashed one
# with format {8}-{4}-{4}-{4}-{12}
data['uuid'] = str(uuidlib.UUID(data['uuid']))
else:
data['uuid'] = uuidutils.generate_uuid()
resource_provider = rp_obj.ResourceProvider(context, **data)
resource_provider.create()
except db_exc.DBDuplicateEntry as exc:
# Whether exc.columns has one or two entries (in the event
# of both fields being duplicates) appears to be database
# dependent, so going with the complete solution here.
duplicate = ', '.join(['%s: %s' % (column, data[column])
for column in exc.columns])
raise webob.exc.HTTPConflict(
_('Conflicting resource provider %(duplicate)s already exists.') %
{'duplicate': duplicate},
comment=errors.DUPLICATE_NAME)
except exception.ObjectActionError as exc:
raise webob.exc.HTTPBadRequest(
_('Unable to create resource provider "%(name)s", %(rp_uuid)s: '
'%(error)s') %
{'name': data['name'], 'rp_uuid': data['uuid'], 'error': exc})
req.response.location = util.resource_provider_url(
req.environ, resource_provider)
if want_version.matches(min_version=(1, 20)):
req.response.body = encodeutils.to_utf8(jsonutils.dumps(
_serialize_provider(req.environ, resource_provider, want_version)))
req.response.content_type = 'application/json'
modified = util.pick_last_modified(None, resource_provider)
req.response.last_modified = modified
req.response.cache_control = 'no-cache'
else:
req.response.status = 201
req.response.content_type = None
return req.response
示例13: set_aggregates
def set_aggregates(req):
microversion.raise_http_status_code_if_not_version(req, 404, (1, 1))
context = req.environ['placement.context']
uuid = util.wsgi_path_item(req.environ, 'uuid')
resource_provider = objects.ResourceProvider.get_by_uuid(
context, uuid)
aggregate_uuids = util.extract_json(req.body, PUT_AGGREGATES_SCHEMA)
resource_provider.set_aggregates(aggregate_uuids)
return _send_aggregates(req.response, aggregate_uuids)
示例14: _extract_inventories
def _extract_inventories(body, schema):
"""Extract and validate multiple inventories from JSON body."""
data = util.extract_json(body, schema)
inventories = {}
for res_class, raw_inventory in data['inventories'].items():
inventory_data = copy.copy(INVENTORY_DEFAULTS)
inventory_data.update(raw_inventory)
inventories[res_class] = inventory_data
data['inventories'] = inventories
return data
示例15: update_resource_provider
def update_resource_provider(req):
"""PUT to update a single resource provider.
On success return a 200 response with a representation of the updated
resource provider.
"""
uuid = util.wsgi_path_item(req.environ, 'uuid')
context = req.environ['placement.context']
context.can(policies.UPDATE)
want_version = req.environ[microversion.MICROVERSION_ENVIRON]
# The containing application will catch a not found here.
resource_provider = rp_obj.ResourceProvider.get_by_uuid(
context, uuid)
schema = rp_schema.PUT_RESOURCE_PROVIDER_SCHEMA
if want_version.matches((1, 14)):
schema = rp_schema.PUT_RP_SCHEMA_V1_14
data = util.extract_json(req.body, schema)
for field in rp_obj.ResourceProvider.SETTABLE_FIELDS:
if field in data:
setattr(resource_provider, field, data[field])
try:
resource_provider.save()
except db_exc.DBDuplicateEntry as exc:
raise webob.exc.HTTPConflict(
_('Conflicting resource provider %(name)s already exists.') %
{'name': data['name']},
comment=errors.DUPLICATE_NAME)
except exception.ObjectActionError as exc:
raise webob.exc.HTTPBadRequest(
_('Unable to save resource provider %(rp_uuid)s: %(error)s') %
{'rp_uuid': uuid, 'error': exc})
response = req.response
response.status = 200
response.body = encodeutils.to_utf8(jsonutils.dumps(
_serialize_provider(req.environ, resource_provider, want_version)))
response.content_type = 'application/json'
if want_version.matches((1, 15)):
response.last_modified = resource_provider.updated_at
response.cache_control = 'no-cache'
return response