本文整理匯總了Python中rapidjson.dumps方法的典型用法代碼示例。如果您正苦於以下問題:Python rapidjson.dumps方法的具體用法?Python rapidjson.dumps怎麽用?Python rapidjson.dumps使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類rapidjson
的用法示例。
在下文中一共展示了rapidjson.dumps方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _unstructure_Path
# 需要導入模塊: import rapidjson [as 別名]
# 或者: from rapidjson import dumps [as 別名]
def _unstructure_Path(path):
data = []
for point in path._points:
ptType = point.type
if ptType is not None:
if point.smooth:
value = (point.x, point.y, ptType, True)
else:
value = (point.x, point.y, ptType)
else:
value = (point.x, point.y)
extraData = point._extraData
if extraData:
value += (extraData,)
data.append(RawJSON(dumps(value)))
if path._extraData:
data.append(path._extraData)
return data
示例2: users
# 需要導入模塊: import rapidjson [as 別名]
# 或者: from rapidjson import dumps [as 別名]
def users(self, request: web.Request):
cached = await RedisDB.instance().get("apiuserscache")
if cached is not None:
return web.json_response(
data=json.loads(cached),
dumps=json.dumps
)
# Get all of not cached
users = await User.all().prefetch_related('account')
resp = []
for user in users:
resp.append(
{
'user_id': user.id,
'user_last_known_name': user.name,
'address': user.account.address,
'created_ts_utc': self.format_js_iso(user.created_at)
}
)
await RedisDB.instance().set("apiuserscache", json.dumps(resp), expires=1800)
return web.json_response(
data=resp,
dumps=json.dumps
)
示例3: test_generic_error_catch
# 需要導入模塊: import rapidjson [as 別名]
# 或者: from rapidjson import dumps [as 別名]
def test_generic_error_catch(server_config):
"""
Test that calculate_and_send_reply_for_message sends a reply if get_reply_for_message raises an unexpected error
"""
mock_socket = Mock()
mock_socket.send_multipart = CoroutineMock()
expected_response = [
"DUMMY_RETURN_ADDRESS",
b"",
rapidjson.dumps(
ZMQReply(status="error", msg="Could not get reply for message")
).encode(),
]
with patch(
"flowmachine.core.server.server.get_reply_for_message"
) as mock_get_reply:
mock_get_reply.side_effect = Exception("Didn't see this one coming!")
await calculate_and_send_reply_for_message(
socket=mock_socket,
return_address="DUMMY_RETURN_ADDRESS",
msg_contents="DUMMY_MESSAGE",
config=server_config,
)
mock_get_reply.assert_called_once()
mock_socket.send_multipart.assert_called_once_with(expected_response)
示例4: serialize
# 需要導入模塊: import rapidjson [as 別名]
# 或者: from rapidjson import dumps [as 別名]
def serialize(data):
"""Serialize a dict into a JSON formatted string.
This function enforces rules like the separator and order of keys.
This ensures that all dicts are serialized in the same way.
This is specially important for hashing data. We need to make sure that
everyone serializes their data in the same way so that we do not have
hash mismatches for the same structure due to serialization
differences.
Args:
data (dict): dict to serialize
Returns:
str: JSON formatted string
"""
return rapidjson.dumps(data, skipkeys=False, ensure_ascii=False,
sort_keys=True)
示例5: _validate_schema
# 需要導入模塊: import rapidjson [as 別名]
# 或者: from rapidjson import dumps [as 別名]
def _validate_schema(schema, body):
"""Validate data against a schema"""
# Note
#
# Schema validation is currently the major CPU bottleneck of
# BigchainDB. the `jsonschema` library validates python data structures
# directly and produces nice error messages, but validation takes 4+ ms
# per transaction which is pretty slow. The rapidjson library validates
# much faster at 1.5ms, however it produces _very_ poor error messages.
# For this reason we use both, rapidjson as an optimistic pathway and
# jsonschema as a fallback in case there is a failure, so we can produce
# a helpful error message.
try:
schema[1](rapidjson.dumps(body))
except ValueError as exc:
try:
jsonschema.validate(body, schema[0])
except jsonschema.ValidationError as exc2:
raise SchemaValidationError(str(exc2)) from exc2
logger.warning('code problem: jsonschema did not raise an exception, wheras rapidjson raised %s', exc)
raise SchemaValidationError(str(exc)) from exc
示例6: test_fulfill_transaction
# 需要導入模塊: import rapidjson [as 別名]
# 或者: from rapidjson import dumps [as 別名]
def test_fulfill_transaction(alice_transaction, alice_sk):
from bigchaindb_driver.offchain import fulfill_transaction
fulfilled_transaction = fulfill_transaction(
alice_transaction, private_keys=alice_sk)
inputs = fulfilled_transaction['inputs']
assert len(inputs) == 1
alice_transaction['inputs'][0]['fulfillment'] = None
message = rapidjson.dumps(
alice_transaction,
skipkeys=False,
ensure_ascii=False,
sort_keys=True,
)
message = sha3_256(message.encode())
fulfillment_uri = inputs[0]['fulfillment']
assert Fulfillment.from_uri(fulfillment_uri).\
validate(message=message.digest())
示例7: get_fcm_tokens
# 需要導入模塊: import rapidjson [as 別名]
# 或者: from rapidjson import dumps [as 別名]
def get_fcm_tokens(account : str, r : web.Request, v2 : bool = False) -> list:
"""Return list of FCM tokens that belong to this account"""
redisInst = r.app['rdata']
tokens = await redisInst.get(account)
if tokens is None:
return []
tokens = json.loads(tokens.replace('\'', '"'))
# Rebuild the list for this account removing tokens that dont belong anymore
new_token_list = {}
new_token_list['data'] = []
if 'data' not in tokens:
return []
for t in tokens['data']:
account_list = await get_or_upgrade_token_account_list(account, t, r, v2=v2)
if account not in account_list:
continue
new_token_list['data'].append(t)
await redisInst.set(account, json.dumps(new_token_list))
return new_token_list['data']
### END Utility functions
# Primary handler for all websocket connections
示例8: work_defer
# 需要導入模塊: import rapidjson [as 別名]
# 或者: from rapidjson import dumps [as 別名]
def work_defer(self, r : web.Request, uid : str, request_json : dict) -> str:
"""Request work_generate, but avoid duplicate requests"""
if request_json['hash'] in r.app['active_work']:
log.server_logger.error('work already requested;%s;%s', self.util.get_request_ip(r), uid)
return None
else:
r.app['active_work'].add(request_json['hash'])
try:
log.server_logger.info('Requesting work for %s;%s', self.util.get_request_ip(r), uid)
response = await self.work_request(request_json)
if response is None:
log.server_logger.error('work defer error; %s;%s', self.util.get_request_ip(r), uid)
return json.dumps({
'error':'work defer error'
})
r.app['active_work'].remove(request_json['hash'])
return response
except Exception:
log.server_logger.exception()
r.app['active_work'].remove(request_json['hash'])
return None
# Server-side check for any incidental mixups due to race conditions or misunderstanding protocol.
# Check blocks submitted for processing to ensure the user or client has not accidentally created a send to an unknown
# address due to balance miscalculation leading to the state block being interpreted as a send rather than a receive.
示例9: _init_json
# 需要導入模塊: import rapidjson [as 別名]
# 或者: from rapidjson import dumps [as 別名]
def _init_json(self):
# rapidjson is well maintained library with acceptable performance, good choice
if self.options['json_lib'] == 'rapidjson':
import rapidjson
self.json_encode = lambda x: rapidjson.dumps(x, number_mode=rapidjson.NM_NATIVE)
self.json_decode = lambda x: rapidjson.loads(x, number_mode=rapidjson.NM_NATIVE)
# ujson provides best performance in our tests, but it is abandoned by maintainers
elif self.options['json_lib'] == 'ujson':
import ujson
self.json_encode = ujson.dumps
self.json_decode = ujson.loads
# json from Python stdlib, very safe choice, but slow
elif self.options['json_lib'] == 'json':
import json
self.json_encode = json.dumps
self.json_decode = json.loads
else:
raise ValueError(f"Unsupported json library [{self.options['json_lib']}]")
示例10: test_asr_get_authz_permissions_from_cache
# 需要導入模塊: import rapidjson [as 別名]
# 或者: from rapidjson import dumps [as 別名]
def test_asr_get_authz_permissions_from_cache(
account_store_realm, monkeypatch, simple_identifier_collection, sample_parts):
asr = account_store_realm
dp = DefaultPermission(parts=sample_parts)
mock_cache = mock.Mock()
mock_cache.hmget_or_create.return_value = [rapidjson.dumps([sample_parts])]
monkeypatch.setattr(asr, 'cache_handler', mock_cache)
result = asr.get_authzd_permissions('thedude', 'domain1')
assert result == [dp]
示例11: test_asr_get_authz_perms_without_cache_from_accountstore
# 需要導入模塊: import rapidjson [as 別名]
# 或者: from rapidjson import dumps [as 別名]
def test_asr_get_authz_perms_without_cache_from_accountstore(
account_store_realm, monkeypatch, simple_identifier_collection,
sample_acct_info, sample_parts):
asr = account_store_realm
dp = DefaultPermission(parts=sample_parts)
monkeypatch.setattr(asr, 'cache_handler', None)
sample = {'domain1': rapidjson.dumps([sample_parts])}
monkeypatch.setattr(asr.account_store, 'get_authz_permissions', lambda x: sample)
result = asr.get_authzd_permissions('thedude', 'domain1')
assert result == [dp]
示例12: dumps
# 需要導入模塊: import rapidjson [as 別名]
# 或者: from rapidjson import dumps [as 別名]
def dumps(obj: object, *args, **kwargs) -> bytes:
kwargs = add_settings_to_kwargs(kwargs)
return rapidjson.dumps(obj, *args, **kwargs)
示例13: ufw
# 需要導入模塊: import rapidjson [as 別名]
# 或者: from rapidjson import dumps [as 別名]
def ufw(self, request: web.Request):
"""Return user info for specified wallet addresses
e.g. http://server/wfu/ban_16n5c7qozokx661rneikh6e3mf978mc46qqjen7a51pwzood155bwrha6sfj+ban_37z6omyukgpgttq7bdagweaxdrdm5wjy7tdm97ggtkobdetme3bmhfayjowj"""
if 'wallet' not in request.match_info:
return web.HTTPBadRequest(reason="wallet is required")
try:
addresses = RegexUtil.find_address_matches(request.match_info['wallet'])
except AddressMissingException:
return web.HTTPBadRequest(reason="bad address specified")
accounts = await Account.filter(address__in=addresses).prefetch_related('user').all()
if accounts is None:
return web.json_response(
data={'error': 'user(s) not found'},
dumps=json.dumps
)
resp = []
for account in accounts:
resp.append(
{
'user_id': account.user.id,
'user_last_known_name': account.user.name,
'address': account.address,
'created_ts_utc': self.format_js_iso(account.user.created_at)
}
)
return web.json_response(
data=resp,
dumps=json.dumps
)
示例14: wfu
# 需要導入模塊: import rapidjson [as 別名]
# 或者: from rapidjson import dumps [as 別名]
def wfu(self, request: web.Request):
"""Return user info for specified discord IDs
e.g. http://server/wfu/303599885800964097+412286270694359052"""
if 'user' not in request.match_info:
return web.HTTPBadRequest(reason="user(s) is required")
user_ids = []
for u in request.match_info['user'].split('+'):
try:
user_ids.append(int(u.strip()))
except ValueError:
return web.HTTPBadRequest(reason="user IDs should be integers")
users = await User.filter(id__in=user_ids).prefetch_related('account').all()
if users is None:
return web.json_response(
data={'error': 'user(s) not found'},
dumps=json.dumps
)
resp = []
for user in users:
resp.append(
{
'user_id': user.id,
'user_last_known_name': user.name,
'address': user.account.address,
'created_ts_utc': self.format_js_iso(user.created_at)
}
)
return web.json_response(
data=resp,
dumps=json.dumps
)
示例15: auto_rain_eligible
# 需要導入模塊: import rapidjson [as 別名]
# 或者: from rapidjson import dumps [as 別名]
def auto_rain_eligible(msg: discord.Message):
# Ignore if user doesnt have rain role
has_rain_role = False
rain_roles = config.Config.instance().get_rain_roles()
if len(rain_roles) > 0:
for role in msg.author.roles:
if role.id in rain_roles:
has_rain_role = True
break
if not has_rain_role:
return
# Get user OBJ from redis if it exists, else create one
user_key = f"activity:{msg.guild.id}:{msg.author.id}"
active_stats = await RedisDB.instance().get(user_key)
if active_stats is None:
# Create stats and save
active_stats = {
'user_id': msg.author.id,
'last_msg': datetime.datetime.utcnow().strftime('%m/%d/%Y %H:%M:%S'),
'msg_count': Constants.RAIN_MSG_REQUIREMENT * 2
}
await RedisDB.instance().set(user_key, json.dumps(active_stats), expires=1800)
return
else:
active_stats = json.loads(active_stats)
if active_stats['msg_count'] < Constants.RAIN_MSG_REQUIREMENT * 2:
active_stats['msg_count'] = Constants.RAIN_MSG_REQUIREMENT * 2
active_stats['last_msg'] = datetime.datetime.utcnow().strftime('%m/%d/%Y %H:%M:%S')
await RedisDB.instance().set(user_key, json.dumps(active_stats), expires=1800)