本文整理汇总了Python中zaqar.transport.utils.to_json函数的典型用法代码示例。如果您正苦于以下问题:Python to_json函数的具体用法?Python to_json怎么用?Python to_json使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了to_json函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: on_get
def on_get(self, req, resp, project_id, queue_name, claim_id):
try:
meta, msgs = self._claim_controller.get(
queue_name,
claim_id=claim_id,
project=project_id)
# Buffer claimed messages
# TODO(kgriffs): Optimize along with serialization (see below)
meta['messages'] = list(msgs)
except storage_errors.DoesNotExist as ex:
LOG.debug(ex)
raise falcon.HTTPNotFound()
except Exception as ex:
LOG.exception(ex)
description = _(u'Claim could not be queried.')
raise wsgi_errors.HTTPServiceUnavailable(description)
# Serialize claimed messages
# TODO(kgriffs): Optimize
base_path = req.path.rsplit('/', 2)[0]
meta['messages'] = [wsgi_utils.format_message_v1_1(msg, base_path,
claim_id)
for msg in meta['messages']]
meta['href'] = req.path
del meta['id']
resp.body = utils.to_json(meta)
示例2: on_get
def on_get(self, request, response, project_id, flavor):
"""Returns a JSON object for a single flavor entry:
::
{"pool_group": "", capabilities: {...}}
:returns: HTTP | [200, 404]
"""
LOG.debug(u'GET flavor - name: %s', flavor)
data = None
detailed = request.get_param_as_bool('detailed') or False
try:
data = self._ctrl.get(flavor,
project=project_id,
detailed=detailed)
# NOTE(wanghao): remove this in Newton.
data['pool'] = data['pool_group']
except errors.FlavorDoesNotExist as ex:
LOG.debug(ex)
raise wsgi_errors.HTTPNotFound(six.text_type(ex))
data['href'] = request.path
response.body = transport_utils.to_json(data)
示例3: on_get
def on_get(self, req, resp, project_id, queue_name, claim_id):
LOG.debug(
u"Claim item GET - claim: %(claim_id)s, " u"queue: %(queue_name)s, project: %(project_id)s",
{"queue_name": queue_name, "project_id": project_id, "claim_id": claim_id},
)
try:
meta, msgs = self._claim_controller.get(queue_name, claim_id=claim_id, project=project_id)
# Buffer claimed messages
# TODO(kgriffs): Optimize along with serialization (see below)
meta["messages"] = list(msgs)
except storage_errors.DoesNotExist as ex:
LOG.debug(ex)
raise falcon.HTTPNotFound()
except Exception as ex:
LOG.exception(ex)
description = _(u"Claim could not be queried.")
raise wsgi_errors.HTTPServiceUnavailable(description)
# Serialize claimed messages
# TODO(kgriffs): Optimize
meta["messages"] = [
wsgi_utils.format_message_v1(msg, req.path.rsplit("/", 2)[0], meta["id"]) for msg in meta["messages"]
]
meta["href"] = req.path
del meta["id"]
resp.content_location = req.relative_uri
resp.body = utils.to_json(meta)
示例4: on_get
def on_get(self, req, resp, project_id, queue_name, message_id):
LOG.debug(u'Messages item GET - message: %(message)s, '
u'queue: %(queue)s, project: %(project)s',
{'message': message_id,
'queue': queue_name,
'project': project_id})
try:
message = self._message_controller.get(
queue_name,
message_id,
project=project_id)
except storage_errors.DoesNotExist as ex:
LOG.debug(ex)
raise falcon.HTTPNotFound()
except Exception as ex:
LOG.exception(ex)
description = _(u'Message could not be retrieved.')
raise wsgi_errors.HTTPServiceUnavailable(description)
# Prepare response
message['href'] = req.path
message = wsgi_utils.format_message_v1_1(message,
req.path.rsplit('/', 2)[0],
message['claim_id'])
resp.body = utils.to_json(message)
示例5: on_get
def on_get(self, request, response, project_id, flavor):
"""Returns a JSON object for a single flavor entry:
::
{"pool": "", capabilities: {...}}
:returns: HTTP | [200, 404]
"""
LOG.debug(u'GET flavor - name: %s', flavor)
data = None
try:
data = self._ctrl.get(flavor, project=project_id)
capabilities = self._pools_ctrl.capabilities(group=data['pool'])
data['capabilities'] = [str(cap).split('.')[-1]
for cap in capabilities]
except errors.FlavorDoesNotExist as ex:
LOG.debug(ex)
raise falcon.HTTPNotFound()
data['href'] = request.path
# remove the name entry - it isn't needed on GET
del data['name']
response.body = transport_utils.to_json(data)
示例6: on_get
def on_get(self, request, response, project_id, pool):
"""Returns a JSON object for a single pool entry:
::
{"weight": 100, "uri": "", options: {...}}
:returns: HTTP | [200, 404]
"""
LOG.debug(u'GET pool - name: %s', pool)
data = None
detailed = request.get_param_as_bool('detailed') or False
try:
data = self._ctrl.get(pool, detailed)
except errors.PoolDoesNotExist as ex:
LOG.debug(ex)
raise falcon.HTTPNotFound()
data['href'] = request.path
# remove the name entry - it isn't needed on GET
del data['name']
response.body = transport_utils.to_json(data)
示例7: _on_get_with_kfilter
def _on_get_with_kfilter(self, req, resp, project_id, kfilter={}):
kwargs = {}
# NOTE(kgriffs): This syntax ensures that
# we don't clobber default values with None.
req.get_param('marker', store=kwargs)
req.get_param_as_int('limit', store=kwargs)
req.get_param_as_bool('detailed', store=kwargs)
req.get_param('name', store=kwargs)
queues, marker = self._queue_list(project_id,
req.path, kfilter, **kwargs)
links = []
kwargs['marker'] = marker
if queues:
links = [
{
'rel': 'next',
'href': req.path + falcon.to_query_str(kwargs)
}
]
response_body = {
'queues': queues,
'links': links
}
resp.body = utils.to_json(response_body)
示例8: on_get
def on_get(self, req, resp, project_id, queue_name):
try:
resp_dict = self._queue_ctrl.stats(queue_name,
project=project_id)
message_stats = resp_dict['messages']
if message_stats['total'] != 0:
base_path = req.path[:req.path.rindex('/')] + '/messages/'
newest = message_stats['newest']
newest['href'] = base_path + newest['id']
del newest['id']
oldest = message_stats['oldest']
oldest['href'] = base_path + oldest['id']
del oldest['id']
resp.content_location = req.path
resp.body = utils.to_json(resp_dict)
# status defaults to 200
except storage_errors.DoesNotExist as ex:
LOG.debug(ex)
raise falcon.HTTPNotFound()
except Exception as ex:
LOG.exception(ex)
description = _(u'Queue stats could not be read.')
raise wsgi_errors.HTTPServiceUnavailable(description)
示例9: on_get
def on_get(self, request, response, project_id, flavor):
"""Returns a JSON object for a single flavor entry:
::
{"pool": "", "pool_list": [], capabilities: {...}}
:returns: HTTP | [200, 404]
"""
LOG.debug(u'GET flavor - name: %s', flavor)
data = None
try:
data = self._ctrl.get(flavor, project=project_id)
capabilities = self._pools_ctrl.capabilities(flavor=data)
data['capabilities'] = [str(cap).split('.')[-1]
for cap in capabilities]
pool_list =\
list(self._pools_ctrl.get_pools_by_flavor(flavor=data))
pool_name_list = []
if len(pool_list) > 0:
pool_name_list = [x['name'] for x in pool_list]
data['pool_list'] = pool_name_list
except errors.FlavorDoesNotExist as ex:
LOG.debug(ex)
raise wsgi_errors.HTTPNotFound(six.text_type(ex))
data['href'] = request.path
response.body = transport_utils.to_json(data)
示例10: on_get
def on_get(self, request, response, project_id, flavor):
"""Returns a JSON object for a single flavor entry:
::
{"pool": "", capabilities: {...}}
:returns: HTTP | [200, 404]
"""
LOG.debug(u"GET flavor - name: %s", flavor)
data = None
try:
data = self._ctrl.get(flavor, project=project_id)
capabilities = self._pools_ctrl.capabilities(group=data["pool"])
data["capabilities"] = [str(cap).split(".")[-1] for cap in capabilities]
except errors.FlavorDoesNotExist as ex:
LOG.debug(ex)
raise falcon.HTTPNotFound()
data["href"] = request.path
response.body = transport_utils.to_json(data)
示例11: on_post
def on_post(self, req, resp, project_id, queue_name):
LOG.debug(u'Pre-Signed URL Creation for queue: %(queue)s, '
u'project: %(project)s',
{'queue': queue_name, 'project': project_id})
try:
document = wsgi_utils.deserialize(req.stream, req.content_length)
except ValueError as ex:
LOG.debug(ex)
raise wsgi_errors.HTTPBadRequestAPI(six.text_type(ex))
diff = set(document.keys()) - _KNOWN_KEYS
if diff:
msg = six.text_type(_LE('Unknown keys: %s') % diff)
raise wsgi_errors.HTTPBadRequestAPI(msg)
key = self._conf.signed_url.secret_key
paths = document.pop('paths', None)
if not paths:
paths = [os.path.join(req.path[:-6], 'messages')]
else:
diff = set(paths) - _VALID_PATHS
if diff:
msg = six.text_type(_LE('Invalid paths: %s') % diff)
raise wsgi_errors.HTTPBadRequestAPI(msg)
paths = [os.path.join(req.path[:-6], path) for path in paths]
try:
data = urls.create_signed_url(key, paths,
project=project_id,
**document)
except ValueError as err:
raise wsgi_errors.HTTPBadRequestAPI(str(err))
resp.body = utils.to_json(data)
示例12: on_post
def on_post(self, req, resp, project_id, queue_name):
if req.content_length:
document = wsgi_utils.deserialize(req.stream, req.content_length)
else:
document = {}
try:
self._validate.subscription_posting(document)
subscriber = document['subscriber']
ttl = int(document['ttl'])
options = document['options']
created = self._subscription_controller.create(queue_name,
subscriber,
ttl,
options,
project=project_id)
except storage_errors.QueueDoesNotExist as ex:
LOG.exception(ex)
raise wsgi_errors.HTTPBadRequestAPI(six.text_type(ex))
except validation.ValidationFailed as ex:
LOG.debug(ex)
raise wsgi_errors.HTTPBadRequestAPI(six.text_type(ex))
except Exception as ex:
LOG.exception(ex)
description = _(u'Subscription could not be created.')
raise wsgi_errors.HTTPServiceUnavailable(description)
resp.status = falcon.HTTP_201 if created else falcon.HTTP_409
resp.location = req.path
if created:
resp.body = utils.to_json(
{'subscription_id': six.text_type(created)})
示例13: on_post
def on_post(self, req, resp, project_id, queue_name):
client_uuid = wsgi_helpers.get_client_uuid(req)
try:
# Place JSON size restriction before parsing
self._validate.message_length(req.content_length)
except validation.ValidationFailed as ex:
LOG.debug(ex)
raise wsgi_errors.HTTPBadRequestAPI(six.text_type(ex))
# Deserialize and validate the incoming messages
document = wsgi_utils.deserialize(req.stream, req.content_length)
if 'messages' not in document:
description = _(u'No messages were found in the request body.')
raise wsgi_errors.HTTPBadRequestAPI(description)
messages = wsgi_utils.sanitize(document['messages'],
self._message_post_spec,
doctype=wsgi_utils.JSONArray)
try:
self._validate.message_posting(messages)
if not self._queue_controller.exists(queue_name, project_id):
self._queue_controller.create(queue_name, project=project_id)
message_ids = self._message_controller.post(
queue_name,
messages=messages,
project=project_id,
client_uuid=client_uuid)
except validation.ValidationFailed as ex:
LOG.debug(ex)
raise wsgi_errors.HTTPBadRequestAPI(six.text_type(ex))
except storage_errors.DoesNotExist as ex:
LOG.debug(ex)
raise falcon.HTTPNotFound()
except storage_errors.MessageConflict as ex:
LOG.exception(ex)
description = _(u'No messages could be enqueued.')
raise wsgi_errors.HTTPServiceUnavailable(description)
except Exception as ex:
LOG.exception(ex)
description = _(u'Messages could not be enqueued.')
raise wsgi_errors.HTTPServiceUnavailable(description)
# Prepare the response
ids_value = ','.join(message_ids)
resp.location = req.path + '?ids=' + ids_value
hrefs = [req.path + '/' + id for id in message_ids]
body = {'resources': hrefs}
resp.body = utils.to_json(body)
resp.status = falcon.HTTP_201
示例14: on_post
def on_post(self, req, resp, project_id, queue_name):
LOG.debug(
u"Messages collection POST - queue: %(queue)s, " u"project: %(project)s",
{"queue": queue_name, "project": project_id},
)
client_uuid = wsgi_helpers.get_client_uuid(req)
try:
# Place JSON size restriction before parsing
self._validate.message_length(req.content_length)
except validation.ValidationFailed as ex:
LOG.debug(ex)
raise wsgi_errors.HTTPBadRequestAPI(six.text_type(ex))
# Deserialize and validate the request body
document = wsgi_utils.deserialize(req.stream, req.content_length)
messages = wsgi_utils.sanitize(document, MESSAGE_POST_SPEC, doctype=wsgi_utils.JSONArray)
try:
self._validate.message_posting(messages)
message_ids = self._message_controller.post(
queue_name, messages=messages, project=project_id, client_uuid=client_uuid
)
except validation.ValidationFailed as ex:
LOG.debug(ex)
raise wsgi_errors.HTTPBadRequestAPI(six.text_type(ex))
except storage_errors.DoesNotExist as ex:
LOG.debug(ex)
raise falcon.HTTPNotFound()
except storage_errors.MessageConflict as ex:
LOG.exception(ex)
description = _(u"No messages could be enqueued.")
raise wsgi_errors.HTTPServiceUnavailable(description)
except Exception as ex:
LOG.exception(ex)
description = _(u"Messages could not be enqueued.")
raise wsgi_errors.HTTPServiceUnavailable(description)
# Prepare the response
ids_value = ",".join(message_ids)
resp.location = req.path + "?ids=" + ids_value
hrefs = [req.path + "/" + id for id in message_ids]
# NOTE(kgriffs): As of the Icehouse release, drivers are
# no longer allowed to enqueue a subset of the messages
# submitted by the client; it's all or nothing. Therefore,
# 'partial' is now always False in the v1.0 API, and the
# field has been removed in v1.1.
body = {"resources": hrefs, "partial": False}
resp.body = utils.to_json(body)
resp.status = falcon.HTTP_201
示例15: on_get
def on_get(self, req, resp, **kwargs):
try:
resp_dict = self._driver.health()
resp.body = utils.to_json(resp_dict)
except Exception as ex:
LOG.exception(ex)
description = _(u'Health status could not be read.')
raise wsgi_errors.HTTPServiceUnavailable(description)