本文整理汇总了Python中ujson.dumps函数的典型用法代码示例。如果您正苦于以下问题:Python dumps函数的具体用法?Python dumps怎么用?Python dumps使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了dumps函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_sending_stream_message_from_electron
def test_sending_stream_message_from_electron(self) -> Generator[str, Any, None]:
user_profile = self.example_user('hamlet')
cookies = self._get_cookies(user_profile)
cookie_header = self.get_cookie_header(cookies)
queue_events_data = self._get_queue_events_data(user_profile.email)
ws = yield self.ws_connect('/sockjs/366/v8nw22qe/websocket', cookie_header=cookie_header)
yield ws.read_message()
yield self._websocket_auth(ws, queue_events_data, cookies)
request_id = ':'.join((queue_events_data['response']['queue_id'], '1'))
user_message = {
"req_id": request_id,
"type": "request",
"request": {
"client": "website",
"type": "stream",
TOPIC_NAME: "Stream message",
"stream": "Denmark",
"private_message_recipient": "",
"content": "hello",
"sender_id": user_profile.id,
"queue_id": queue_events_data['response']['queue_id'],
"to": ujson.dumps(["Denmark"]),
"reply_to": self.example_email('hamlet'),
"local_id": -1,
"socket_user_agent": "ZulipElectron/1.5.0"
}
}
user_message_str = ujson.dumps(user_message)
ws.write_message(ujson.dumps([user_message_str]))
ack_resp = yield ws.read_message()
msg_resp = yield ws.read_message()
self._check_message_sending(request_id, ack_resp, msg_resp, user_profile, queue_events_data)
yield self.close(ws)
示例2: testEncodeUnicodeBMP
def testEncodeUnicodeBMP(self):
s = u'\U0001f42e\U0001f42e\U0001F42D\U0001F42D' # 🐮🐮🐭🐭
encoded = ujson.dumps(s)
encoded_json = json.dumps(s)
if len(s) == 4:
self.assertEqual(len(encoded), len(s) * 12 + 2)
else:
self.assertEqual(len(encoded), len(s) * 6 + 2)
self.assertEqual(encoded, encoded_json)
decoded = ujson.loads(encoded)
self.assertEqual(s, decoded)
# ujson outputs an UTF-8 encoded str object
if PY3:
encoded = ujson.dumps(s, ensure_ascii=False)
else:
encoded = ujson.dumps(s, ensure_ascii=False).decode("utf-8")
# json outputs an unicode object
encoded_json = json.dumps(s, ensure_ascii=False)
self.assertEqual(len(encoded), len(s) + 2) # original length + quotes
self.assertEqual(encoded, encoded_json)
decoded = ujson.loads(encoded)
self.assertEqual(s, decoded)
示例3: test_change_regular_member_to_guest
def test_change_regular_member_to_guest(self) -> None:
iago = self.example_user("iago")
self.login(iago.email)
hamlet = self.example_user("hamlet")
self.assertFalse(hamlet.is_guest)
# Test failure of making user both admin and guest
req = dict(is_guest=ujson.dumps(True), is_admin=ujson.dumps(True))
result = self.client_patch('/json/users/{}'.format(hamlet.id), req)
self.assert_json_error(result, 'Guests cannot be organization administrators')
self.assertFalse(hamlet.is_guest)
self.assertFalse(hamlet.is_realm_admin)
hamlet = self.example_user("hamlet")
req = dict(is_guest=ujson.dumps(True))
events = [] # type: List[Mapping[str, Any]]
with tornado_redirected_to_list(events):
result = self.client_patch('/json/users/{}'.format(hamlet.id), req)
self.assert_json_success(result)
hamlet = self.example_user("hamlet")
self.assertTrue(hamlet.is_guest)
person = events[0]['event']['person']
self.assertEqual(person['email'], hamlet.email)
self.assertTrue(person['is_guest'])
示例4: index_reviews
def index_reviews(self, reviewed_pages, reviews_count, batch_size):
action = {'index': {'_type': 'review'}}
for i in range(0, reviews_count, batch_size):
body_bits = []
for page in reviewed_pages[i:i + batch_size]:
doc = self.gen_doc(page.last_review)
action['index']['_id'] = doc['page_id']
body_bits.append(dumps(action))
body_bits.append(dumps(doc))
# Yes, that trailing newline IS necessary
body = '\n'.join(body_bits) + '\n'
self.syncES.send_request(
method='POST',
path_components=[self.index, '_bulk'],
body=body,
encode_body=False
)
logging.info('Done!')
示例5: _render_hits
def _render_hits(item):
rslt = item['metrics']['hits']['hits'][0]['_source']
if flag['is_first']:
flag['is_first'] = False
return json.dumps(rslt)
else:
return ',' + json.dumps(rslt)
示例6: __call__
def __call__(self, parsed_json):
flattened = self._flatten(parsed_json)
for distribution_set in args.distribution or ():
flattened_subset = tuple( (k,v) for k,v in flattened.iteritems() if k.startswith(distribution_set) and k != distribution_set )
sum_subset = sum( v for (_,v) in flattened_subset )
flattened.update( (k,float(v)/(sum_subset or 1)) for (k,v) in flattened_subset )
found_keys = set()
at_least_one_found = False
for (k,_) in self._keys:
result = flattened.pop(k, self._missing_marker)
if (result not in (dict, self._missing_marker)):
yield result
at_least_one_found = True
k = k.split('/')
while k:
found_keys.add('/'.join(k))
k = k[0:-1]
elif result is dict:
raise ValueError('%s is a container in %s' % (k, json.dumps(parsed_json))) # pylint: disable=E1101
elif args.ignore_missing or k in self._defaults:
yield self._defaults.get(k, "")
k = k.split('/')
while k:
found_keys.add('/'.join(k))
k = k[0:-1]
else:
raise ValueError('Cannot extract %s from %s' % (k, json.dumps(parsed_json))) # pylint: disable=E1101
if args.add_unparsed:
yield '' if at_least_one_found else json.dumps(parsed_json)
if (not args.ignore_surplus):
flattened = ', '.join( '%s: %s' % (k, str(v)) for k,v in flattened.iteritems() if v and (v is not dict) and k not in found_keys )
if flattened:
raise ValueError('Found extra values ' + flattened)
示例7: common_subscribe_to_streams
def common_subscribe_to_streams(self, email, streams, extra_post_data={}, invite_only=False):
# type: (Text, Iterable[Text], Dict[str, Any], bool) -> HttpResponse
post_data = {'subscriptions': ujson.dumps([{"name": stream} for stream in streams]),
'invite_only': ujson.dumps(invite_only)}
post_data.update(extra_post_data)
result = self.client_post("/api/v1/users/me/subscriptions", post_data, **self.api_auth(email))
return result
示例8: handle_message
def handle_message(self, s, e):
self.logger.debug('message received')
m = s.recv_multipart()
id, mtype, token, data = m
if isinstance(data, basestring):
try:
data = json.loads(data)
except ValueError as e:
self.logger.error(e)
self.router.send_multipart(["", json.dumps({"status": "failed" })])
handler = getattr(self, "handle_" + mtype)
if handler:
self.logger.debug("mtype: {0}".format(mtype))
self.logger.debug('running handler: {}'.format(mtype))
try:
rv = handler(token, data)
rv = {"status": "success", "data": rv}
except Exception as e:
self.logger.error(e)
rv = {"status": "failed"}
rv = json.dumps(rv)
self.router.send_multipart([id, rv])
else:
self.logger.error('message type {0} unknown'.format(mtype))
self.router.send_multipart([id, '0'])
示例9: make_response
def make_response(self, request, response):
"""Convert a handler result to web response."""
while iscoroutine(response):
response = yield from response
if isinstance(response, StreamResponse):
return response
if isinstance(response, str):
return Response(text=response, content_type='text/html', charset=self.app.cfg.ENCODING)
if isinstance(response, (list, dict)):
return Response(text=json.dumps(response), content_type='application/json')
if isinstance(response, (MultiDict, MultiDictProxy)):
response = dict(response)
return Response(text=json.dumps(response), content_type='application/json')
if isinstance(response, bytes):
response = Response(
body=response, content_type='text/html', charset=self.app.cfg.ENCODING)
return response
if response is None:
response = ''
return Response(text=str(response), content_type='text/html')
示例10: test_REQ_converter
def test_REQ_converter(self):
def my_converter(data):
lst = ujson.loads(data)
if not isinstance(lst, list):
raise ValueError('not a list')
if 13 in lst:
raise JsonableError('13 is an unlucky number!')
return lst
@has_request_variables
def get_total(request, numbers=REQ(converter=my_converter)):
return sum(numbers)
class Request(object):
REQUEST = {} # type: Dict[str, str]
request = Request()
with self.assertRaises(RequestVariableMissingError):
get_total(request)
request.REQUEST['numbers'] = 'bad_value'
with self.assertRaises(RequestVariableConversionError) as cm:
get_total(request)
self.assertEqual(str(cm.exception), "Bad value for 'numbers': bad_value")
request.REQUEST['numbers'] = ujson.dumps([2, 3, 5, 8, 13, 21])
with self.assertRaises(JsonableError) as cm:
get_total(request)
self.assertEqual(str(cm.exception), "13 is an unlucky number!")
request.REQUEST['numbers'] = ujson.dumps([1, 2, 3, 4, 5, 6])
result = get_total(request)
self.assertEqual(result, 21)
示例11: test_REQ_validator
def test_REQ_validator(self):
@has_request_variables
def get_total(request, numbers=REQ(validator=check_list(check_int))):
return sum(numbers)
class Request(object):
REQUEST = {} # type: Dict[str, str]
request = Request()
with self.assertRaises(RequestVariableMissingError):
get_total(request)
request.REQUEST['numbers'] = 'bad_value'
with self.assertRaises(JsonableError) as cm:
get_total(request)
self.assertEqual(str(cm.exception), 'argument "numbers" is not valid json.')
request.REQUEST['numbers'] = ujson.dumps([1, 2, "what?", 4, 5, 6])
with self.assertRaises(JsonableError) as cm:
get_total(request)
self.assertEqual(str(cm.exception), 'numbers[2] is not an integer')
request.REQUEST['numbers'] = ujson.dumps([1, 2, 3, 4, 5, 6])
result = get_total(request)
self.assertEqual(result, 21)
示例12: insert_graph_receipt_txn
def insert_graph_receipt_txn(self, txn, room_id, receipt_type,
user_id, event_ids, data):
txn.call_after(
self.get_receipts_for_room.invalidate, (room_id, receipt_type)
)
txn.call_after(
self._invalidate_get_users_with_receipts_in_room,
room_id, receipt_type, user_id,
)
txn.call_after(
self.get_receipts_for_user.invalidate, (user_id, receipt_type)
)
# FIXME: This shouldn't invalidate the whole cache
txn.call_after(self.get_linearized_receipts_for_room.invalidate_many, (room_id,))
self._simple_delete_txn(
txn,
table="receipts_graph",
keyvalues={
"room_id": room_id,
"receipt_type": receipt_type,
"user_id": user_id,
}
)
self._simple_insert_txn(
txn,
table="receipts_graph",
values={
"room_id": room_id,
"receipt_type": receipt_type,
"user_id": user_id,
"event_ids": json.dumps(event_ids),
"data": json.dumps(data),
}
)
示例13: send
def send(self, service_req):
"""Send will wait for a response with a listener and is async
"""
service_req.conn_id = uuid4().hex
header = "%s %s %s %s %s %s %s %s %s" % (self.sender_id,
t(service_req.conn_id),
t(service_req.request_timestamp),
t(self.passphrase),
t(service_req.origin_sender_id),
t(service_req.origin_conn_id),
t(service_req.origin_out_addr),
t(service_req.path),
t(service_req.method),
)
arguments = to_bytes(json.dumps(service_req.arguments))
headers = to_bytes(json.dumps(service_req.headers))
body = to_bytes(json.dumps(service_req.body))
msg = ' %s %s%s%s' % (header, t(arguments),t(headers), t(body))
logging.debug(
"ServiceClientConnection send (%s:%s): %s" % (self.sender_id, service_req.conn_id, msg)
)
self.out_sock.send(msg)
return service_req
示例14: UploadPhoto
def UploadPhoto(self, token, albumid):
name = 'test2%d' % int(time.time())
filename = './2.png'
content = open(filename, 'r').read()
sha = hashlib.sha1()
sha.update(content)
sha1 = sha.hexdigest()
# first commit
data = {'token' : token,
'latitude':40.0425140000, 'longitude': 116.3293040000,
'sha1' : sha1, 'albumid' : albumid,
'tag' : ['测试中文标签', 'test english tag', '第三个测试标签']}
data = ujson.dumps(data)
res = self.api('commit', data)
if res['result_code'] == 10000:
assert res['photoid'] is not None
photoid = res['photoid']
else:
assert res['result_code'] == 14004, res
#upload file
res = ossmisc.uploadFile(sha1, content)
assert res == 10000
# true commit
data = {'token' : token, 'latitude':40.0425140000, 'longitude': 116.3293040000, 'sha1' : sha1, 'albumid' : albumid}
data = ujson.dumps(data)
res = self.api('commit', data)
assert res['result_code'] == 10000
photoid = res['photoid']
return photoid
示例15: test_change_signup_notifications_stream
def test_change_signup_notifications_stream(self) -> None:
# We need an admin user.
email = '[email protected]'
self.login(email)
disabled_signup_notifications_stream_id = -1
req = dict(signup_notifications_stream_id = ujson.dumps(disabled_signup_notifications_stream_id))
result = self.client_patch('/json/realm', req)
self.assert_json_success(result)
realm = get_realm('zulip')
self.assertEqual(realm.signup_notifications_stream, None)
new_signup_notifications_stream_id = 4
req = dict(signup_notifications_stream_id = ujson.dumps(new_signup_notifications_stream_id))
result = self.client_patch('/json/realm', req)
self.assert_json_success(result)
realm = get_realm('zulip')
self.assertEqual(realm.signup_notifications_stream.id, new_signup_notifications_stream_id)
invalid_signup_notifications_stream_id = 1234
req = dict(signup_notifications_stream_id = ujson.dumps(invalid_signup_notifications_stream_id))
result = self.client_patch('/json/realm', req)
self.assert_json_error(result, 'Invalid stream id')
realm = get_realm('zulip')
self.assertNotEqual(realm.signup_notifications_stream.id, invalid_signup_notifications_stream_id)