本文整理汇总了Python中ujson.dumps方法的典型用法代码示例。如果您正苦于以下问题:Python ujson.dumps方法的具体用法?Python ujson.dumps怎么用?Python ujson.dumps使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ujson
的用法示例。
在下文中一共展示了ujson.dumps方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: json
# 需要导入模块: import ujson [as 别名]
# 或者: from ujson import dumps [as 别名]
def json(
body,
status=200,
headers=None,
content_type="application/json",
dumps=json_dumps,
**kwargs,
):
"""
Returns response object with body in json format.
:param body: Response data to be serialized.
:param status: Response code.
:param headers: Custom Headers.
:param kwargs: Remaining arguments that are passed to the json encoder.
"""
return HTTPResponse(
dumps(body, **kwargs),
headers=headers,
status=status,
content_type=content_type,
)
示例2: __require_rename_table
# 需要导入模块: import ujson [as 别名]
# 或者: from ujson import dumps [as 别名]
def __require_rename_table(self, src_con: SimpleSQLite, src_table_name: str) -> bool:
if not self.__dst_con.has_table(src_table_name):
return False
lhs = self.__dst_con.schema_extractor.fetch_table_schema(src_table_name).as_dict()
rhs = src_con.schema_extractor.fetch_table_schema(src_table_name).as_dict()
if lhs != rhs:
self.__logger.debug(
dedent(
"""\
require rename '{table}' because of src table and dst table has
a different schema with the same table name:
dst-schema={dst_schema}
src-schema={src_schema}
"""
).format(
table=src_table_name,
src_schema=json.dumps(lhs, indent=4, ensure_ascii=False),
dst_schema=json.dumps(rhs, indent=4, ensure_ascii=False),
)
)
return True
return False
示例3: convert
# 需要导入模块: import ujson [as 别名]
# 或者: from ujson import dumps [as 别名]
def convert(self) -> Set[str]:
if not self.__metadata:
self._logger.debug("metadata not found")
return set()
self.__convert_kernelspec()
self.__convert_language_info()
self.__convert_kv()
if self.__metadata:
self._logger.debug(
"cannot convert: {}".format(
json.dumps(self.__metadata, indent=4, ensure_ascii=False)
)
)
return self._changed_table_name_set
示例4: on_get
# 需要导入模块: import ujson [as 别名]
# 或者: from ujson import dumps [as 别名]
def on_get(self, req, resp):
# Username verified in auth middleware
username = req.context['user']
access_token = hashlib.sha256(os.urandom(32)).hexdigest()
encrypted_token = self.fernet.encrypt(access_token.encode('utf8'))
exp = time.time() + self.access_ttl
connection = db.connect()
cursor = connection.cursor()
try:
cursor.execute('''INSERT INTO `access_token` (`user_id`, `key`, `expiration`)
VALUES ((SELECT `id` FROM `target` WHERE `name` = %s AND `type_id` =
(SELECT `id` FROM `target_type` WHERE `name` = 'user')),
%s,
%s)''',
(username, encrypted_token, exp))
connection.commit()
key_id = cursor.lastrowid
finally:
cursor.close()
connection.close()
resp.body = ujson.dumps({'token': access_token, 'key_id': key_id, 'expiry': exp})
示例5: update_stats
# 需要导入模块: import ujson [as 别名]
# 或者: from ujson import dumps [as 别名]
def update_stats(self):
url = "https://bots.discord.pw/api/bots/{}/stats".format(self.user.id)
while not self.is_closed():
payload = json.dumps(dict(server_count=len(self.guilds))).encode()
headers = {'authorization': self._auth[1], "Content-Type": "application/json"}
async with self.session.post(url, data=payload, headers=headers) as response:
await response.read()
url = "https://discordbots.org/api/bots/{}/stats".format(self.user.id)
payload = json.dumps(dict(server_count=len(self.guilds))).encode()
headers = {'authorization': self._auth[2], "Content-Type": "application/json"}
async with self.session.post(url, data=payload, headers=headers) as response:
await response.read()
await asyncio.sleep(14400)
示例6: _merge_status
# 需要导入模块: import ujson [as 别名]
# 或者: from ujson import dumps [as 别名]
def _merge_status(self, nodename, status):
currstatus = self._status.get(nodename, None)
if currstatus is not None:
if currstatus.get('clock', -1) > status.get('clock', -2):
LOG.error('old clock: {} > {} - dropped'.format(
currstatus.get('clock', -1),
status.get('clock', -2)
))
return
self._status[nodename] = status
try:
source = nodename.split(':', 2)[2]
self.SR.publish(
'mm-engine-status.'+source,
ujson.dumps({
'source': source,
'timestamp': int(time.time())*1000,
'status': status
})
)
except:
LOG.exception('Error publishing status')
示例7: _build_iterator
# 需要导入模块: import ujson [as 别名]
# 或者: from ujson import dumps [as 别名]
def _build_iterator(self, now):
if self.api_key is None or self.label is None:
raise RuntimeError(
'%s - api_key or label not set, poll not performed' % self.name
)
body = {
'label': self.label,
'panosFormatted': True
}
af = pan.afapi.PanAFapi(
hostname=self.hostname,
verify_cert=self.verify_cert,
api_key=self.api_key
)
r = af.export(data=ujson.dumps(body))
r.raise_for_status()
return r.json.get('export_list', [])
示例8: _xmpp_publish
# 需要导入模块: import ujson [as 别名]
# 或者: from ujson import dumps [as 别名]
def _xmpp_publish(self, cmd, data=None):
if data is None:
data = ''
payload_xml = sleekxmpp.xmlstream.ET.Element('mm-command')
command_xml = sleekxmpp.xmlstream.ET.SubElement(payload_xml, 'command')
command_xml.text = cmd
seqno_xml = sleekxmpp.xmlstream.ET.SubElement(payload_xml, 'seqno')
seqno_xml.text = '%s' % self.sequence_number
data_xml = sleekxmpp.xmlstream.ET.SubElement(payload_xml, 'data')
data_xml.text = ujson.dumps(data)
result = self._xmpp_client['xep_0060'].publish(
self.pubsub_service,
self.node,
payload=payload_xml
)
LOG.debug('%s - xmpp publish: %s', self.name, result)
self.sequence_number += 1
self.statistics['xmpp.published'] += 1
示例9: test_writer
# 需要导入模块: import ujson [as 别名]
# 或者: from ujson import dumps [as 别名]
def test_writer(self):
config = {}
comm = comm_mock.comm_factory(config)
store = traced_mock.store_factory()
writer = minemeld.traced.writer.Writer(comm, store, 'TESTTOPIC')
self.assertEqual(comm.sub_channels[0]['topic'], 'TESTTOPIC')
self.assertEqual(comm.sub_channels[0]['allowed_methods'], ['log'])
writer.log(0, log='testlog')
self.assertEqual(store.writes[0]['timestamp'], 0)
self.assertEqual(store.writes[0]['log'], ujson.dumps({'log': 'testlog'}))
writer.stop()
writer.log(0, log='testlog')
self.assertEqual(len(store.writes), 1)
writer.stop() # just for coverage
示例10: test_get_list_from_recorder
# 需要导入模块: import ujson [as 别名]
# 或者: from ujson import dumps [as 别名]
def test_get_list_from_recorder(recorder):
msg1, frm1 = 'm1', 'f1'
msg2, frm2 = 'm2', 'f2'
msg3, to1, to11 = 'm3', 't1', 't11'
# Decrease resolution
recorder.TIME_FACTOR = 1
time.sleep(1)
recorder.add_outgoing(msg3, to1, to11)
recorder.add_incoming(msg1, frm1)
recorder.add_incoming(msg2, frm2)
recorder.add_disconnecteds('a', 'b', 'c')
for k, v in recorder.store.iterator(include_value=True):
assert v.decode() == json.dumps([
[Recorder.OUTGOING_FLAG, 'm3', 't1', 't11'],
[Recorder.INCOMING_FLAG, 'm1', 'f1'],
[Recorder.INCOMING_FLAG, 'm2', 'f2'],
[Recorder.DISCONN_FLAG, 'a', 'b', 'c']
])
示例11: call
# 需要导入模块: import ujson [as 别名]
# 或者: from ujson import dumps [as 别名]
def call(self, url, params=None):
'''Actually make the API call with the given params - this should only be called by the namespace methods - use the helpers in regular usage like m.tags.list()'''
if params is None: params = {}
params['key'] = self.apikey
params = json.dumps(params)
self.log('POST to %s%s.json: %s' % (ROOT, url, params))
start = time.time()
r = self.session.post('%s%s.json' % (ROOT, url), data=params, headers={'content-type': 'application/json', 'user-agent': 'Mandrill-Python/1.0.55'})
try:
remote_addr = r.raw._original_response.fp._sock.getpeername() # grab the remote_addr before grabbing the text since the socket will go away
except:
remote_addr = (None, None) #we use two private fields when getting the remote_addr, so be a little robust against errors
response_body = r.text
complete_time = time.time() - start
self.log('Received %s in %.2fms: %s' % (r.status_code, complete_time * 1000, r.text))
self.last_request = {'url': url, 'request_body': params, 'response_body': r.text, 'remote_addr': remote_addr, 'response': r, 'time': complete_time}
result = json.loads(response_body)
if r.status_code != requests.codes.ok:
raise self.cast_error(result)
return result
示例12: model
# 需要导入模块: import ujson [as 别名]
# 或者: from ujson import dumps [as 别名]
def model(message):
sentence = json.loads(message)
doc = nlp(sentence)
entities = nlp(sentence).ents
if len(entities) == 0:
return None
ner = dict(
sentence=sentence,
entities=[str(e) for e in entities]
)
cat, score = predict_sentiment(ner['sentence'])
output = [dict(
entity=entity,
sentiment=cat,
score=score
) for entity in ner['entities']]
return json.dumps(output)
示例13: redis
# 需要导入模块: import ujson [as 别名]
# 或者: from ujson import dumps [as 别名]
def redis(self, stream='comments'):
r : redis.Redis = redis.Redis(host=REDIS_HOST)
try:
s = self.sub.stream
s = s.comments if stream == 'comments' else s.submissions
f = extract_comment if stream == 'comments' else extract_post
for c in tqdm(s()):
msg = f(c)
text = replace_urls(msg['text'])
sentences = message_to_sentences(text)
for s in sentences:
r.publish(stream, ujson.dumps(s))
author = msg['author']
key = f'{stream}:{author}'
r.incr(key)
r.expire(key, 3600*24)
except APIException as e:
print(e)
self.__retry()
except ClientException as e:
print(e)
self.__retry()
示例14: redis
# 需要导入模块: import ujson [as 别名]
# 或者: from ujson import dumps [as 别名]
def redis(self, stream='comments'):
r : redis.Redis = redis.Redis(host=REDIS_HOST)
try:
s = self.sub.stream
s = s.comments if stream == 'comments' else s.submissions
f = extract_comment if stream == 'comments' else extract_post
for c in tqdm(s()):
msg = f(c)
r.publish(stream, ujson.dumps(msg))
author = msg['author']
key = f'{stream}:{author}'
r.incr(key)
r.expire(key, 3600*24)
except APIException as e:
print(e)
self.__retry()
except ClientException as e:
print(e)
self.__retry()
示例15: format_results
# 需要导入模块: import ujson [as 别名]
# 或者: from ujson import dumps [as 别名]
def format_results(self, results):
#print('format_results: label=%s results=%s' % (self.label, results))
if self.label == 'account_data':
results = self.format_account_data(results)
elif self.label == 'positions':
results = self.format_positions(results)
elif self.label == 'orders':
results = self.format_orders(results)
elif self.label == 'tickets':
results = self.format_tickets(results)
elif self.label=='executions':
results = self.format_executions(results)
elif self.label == 'order_status':
results = self.format_orders(results, self.id)
elif self.label == 'barchart':
results = self.api.format_barchart(results)
return json.dumps(results)