本文整理汇总了Python中cbor.loads方法的典型用法代码示例。如果您正苦于以下问题:Python cbor.loads方法的具体用法?Python cbor.loads怎么用?Python cbor.loads使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cbor
的用法示例。
在下文中一共展示了cbor.loads方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: detag
# 需要导入模块: import cbor [as 别名]
# 或者: from cbor import loads [as 别名]
def detag(val):
""" Decode CBOR if necessary
-> decoded_object, was_CBOR"""
try:
return cbor.loads(val), True
except:
try:
if val.tag == 24:
return cbor.loads(val.value), True
except:
return val, False
###################################
# Function to negotiate as initiator
# to get DNS records
###################################
示例2: get_block_by_id
# 需要导入模块: import cbor [as 别名]
# 或者: from cbor import loads [as 别名]
def get_block_by_id(self, st, block_id):
_debug('get_block_by_id %s', block_id)
if not block_id:
return
with self.env.begin(db=self.block_db) as t:
r = t.get(block_id)
if not r:
return
r = cbor.loads(r)
block_data, block_refcnt, block_type = r
assert isinstance(block_data, bytes)
assert isinstance(block_refcnt, int)
block_data = block_data or None
block_data = self.codec.decode_block(block_id, block_data)
b = storage.StoredBlock(st, block_id, refcnt=block_refcnt, data=block_data,
type=block_type)
return b
示例3: loads
# 需要导入模块: import cbor [as 别名]
# 或者: from cbor import loads [as 别名]
def loads(cls, data):
'''Create a feature collection from a CBOR byte string.'''
rep = cbor.loads(data)
if not isinstance(rep, Sequence):
raise SerializationError('expected a CBOR list')
if len(rep) != 2:
raise SerializationError('expected a CBOR list of 2 items')
metadata = rep[0]
if 'v' not in metadata:
raise SerializationError('no version in CBOR metadata')
if metadata['v'] != 'fc01':
raise SerializationError('invalid CBOR version {!r} '
'(expected "fc01")'
.format(metadata['v']))
read_only = metadata.get('ro', False)
contents = rep[1]
return cls.from_dict(contents, read_only=read_only)
示例4: _decode_transaction
# 需要导入模块: import cbor [as 别名]
# 或者: from cbor import loads [as 别名]
def _decode_transaction(transaction):
try:
content = cbor.loads(transaction.payload)
except:
raise InvalidTransaction('Invalid payload serialization')
try:
verb = content['Verb']
except AttributeError:
raise InvalidTransaction('Verb is required')
try:
name = content['Name']
except AttributeError:
raise InvalidTransaction('Name is required')
try:
value = content['Value']
except AttributeError:
raise InvalidTransaction('Value is required')
return verb, name, value
示例5: __init__
# 需要导入模块: import cbor [as 别名]
# 或者: from cbor import loads [as 别名]
def __init__(self, conf_file, privkey_file=None, elem_id=None):
self.my_id = elem_id
with open(conf_file, "rb") as f:
dict_ = cbor.loads(f.read())
self.threshold = dict_["threshold"]
self.logs = {}
for log_id in dict_["logs"]:
self.logs[log_id] = ConfElem(*dict_["logs"][log_id])
self.monitors = {}
for monitor_id in dict_["monitors"]:
self.monitors[monitor_id] = ConfElem(*dict_["monitors"][monitor_id])
self.privkey = None
if privkey_file:
with open(privkey_file, "rb") as f:
self.privkey = SigningKey(f.read())
示例6: object_for_bytes
# 需要导入模块: import cbor [as 别名]
# 或者: from cbor import loads [as 别名]
def object_for_bytes(obj_bytes):
try:
decoded = cbor.loads(obj_bytes)
if isinstance(decoded, dict):
return decoded
except ValueError:
pass
return obj_bytes
示例7: detag
# 需要导入模块: import cbor [as 别名]
# 或者: from cbor import loads [as 别名]
def detag(val):
""" Decode CBOR if necessary
-> decoded_object, was_CBOR"""
try:
return cbor.loads(val), True
except:
try:
if val.tag == 24:
return cbor.loads(val.value), True
except:
return val, False
####################################
# Support functions for negotiator
####################################
示例8: _ass_obj
# 需要导入模块: import cbor [as 别名]
# 或者: from cbor import loads [as 别名]
def _ass_obj(x):
"""Internal use only"""
######################################
# Assemble an objective ready for CBOR
######################################
obj_flags = _flagword(x)
_val = x.value
if tname(_val) == "bytes":
#see if user supplied value as CBOR bytes
try:
_ = cbor.loads(x.value)
#seems to be valid CBOR, build Tag 24
_tag24 = cbor.cbor.Tag(tag=24)
_length = len(_val)
#be lazy, don't optimise CBOR encoding
if _length<65536:
_tag24.value = bytes.fromhex('59')+_length.to_bytes(2,byteorder='big')+_val
_val = _tag24
else:
#byte string too big, we'll send the raw bytes
pass
except:
#not valid CBOR, we'll send the raw bytes
pass
return [x.name, obj_flags, x.loop_count, _val]
示例9: load_external_dict_to
# 需要导入模块: import cbor [as 别名]
# 或者: from cbor import loads [as 别名]
def load_external_dict_to(self, d, o):
self.set_external_dict_to(cbor.loads(d), o)
return o
示例10: _loads
# 需要导入模块: import cbor [as 别名]
# 或者: from cbor import loads [as 别名]
def _loads(s):
return json.loads(s, cls=_WAMPJsonDecoder)
示例11: unserialize
# 需要导入模块: import cbor [as 别名]
# 或者: from cbor import loads [as 别名]
def unserialize(self, payload):
"""
Implements :func:`autobahn.wamp.interfaces.IObjectSerializer.unserialize`
"""
if self._batched:
msgs = []
N = len(payload)
i = 0
while i < N:
# read message length prefix
if i + 4 > N:
raise Exception("batch format error [1]")
l = struct.unpack("!L", payload[i:i + 4])[0]
# read message data
if i + 4 + l > N:
raise Exception("batch format error [2]")
data = payload[i + 4:i + 4 + l]
# append parsed raw message
msgs.append(cbor.loads(data))
# advance until everything consumed
i = i + 4 + l
if i != N:
raise Exception("batch format error [3]")
return msgs
else:
unpacked = cbor.loads(payload)
return [unpacked]
示例12: unpack_artifact_row
# 需要导入模块: import cbor [as 别名]
# 或者: from cbor import loads [as 别名]
def unpack_artifact_row(row):
data = {
'url': row['f:url'],
'timestamp': int(row['f:timestamp']),
'request': {
'method': row['f:request.method'],
'client': cbor.loads(zlib.decompress(row['f:request.client'])),
'headers': cbor.loads(zlib.decompress(row['f:request.headers'])),
'body': cbor.loads(zlib.decompress(row['f:request.body'])),
},
'response': {
'status': row['f:response.status'],
'server': {
'hostname': row['f:response.server.hostname'],
'address': row['f:response.server.address'],
},
'headers': cbor.loads(zlib.decompress(row['f:response.headers'])),
'body': cbor.loads(zlib.decompress(row['f:response.body'])),
},
'indices': [],
}
for kk, vv in row.items():
mm = re.match(r"^f:index\.(?P<key>.*)\.[0-9]+$", kk)
if mm is not None:
data['indices'].append((mm.group('key'), vv))
return data
示例13: from_kvlayer
# 需要导入模块: import cbor [as 别名]
# 或者: from cbor import loads [as 别名]
def from_kvlayer(key, data, path=None):
data = cbor.loads(data)
meta_data = data['meta_data']
user_data = data['user_data']
factory = Item
if data.get('is_folder', False):
factory = Folder
return factory(namespace=uni(key[0]), owner=uni(key[1]), inode=key[2],
path=path, meta_data=meta_data, data=user_data)
示例14: register_serializer
# 需要导入模块: import cbor [as 别名]
# 或者: from cbor import loads [as 别名]
def register_serializer(feature_type, obj):
'''
This is a **class** method that lets you define your own
feature type serializers. ``tag`` should be the name of
the feature type that you want to define serialization
for. Currently, the valid values are ``StringCounter``,
``Unicode``, ``SparseVector`` or ``DenseVector``.
Note that this function is not thread safe.
``obj`` must be an object with three attributes defined.
``obj.loads`` is a function that takes a CBOR created
Python data structure and returns a new feature counter.
``obj.dumps`` is a function that takes a feature counter
and returns a Python data structure that can be serialized
by CBOR.
``obj.constructor`` is a function with no parameters that
returns the Python ``type`` that can be used to construct
new features. It should be possible to call
``obj.constructor()`` to get a new and empty feature
counter.
'''
registry.add(feature_type, obj)
示例15: add
# 需要导入模块: import cbor [as 别名]
# 或者: from cbor import loads [as 别名]
def add(self, name, obj):
'''Register a new feature serializer.
The feature type should be one of the fixed set of feature
representations, and `name` should be one of ``StringCounter``,
``SparseVector``, or ``DenseVector``. `obj` is a describing
object with three fields: `constructor` is a callable that
creates an empty instance of the representation; `dumps` is
a callable that takes an instance of the representation and
returns a JSON-compatible form made of purely primitive
objects (lists, dictionaries, strings, numbers); and `loads`
is a callable that takes the response from `dumps` and recreates
the original representation.
Note that ``obj.constructor()`` *must* return an
object that is an instance of one of the following
types: ``unicode``, :class:`memex_dossier.fc.StringCounter`,
:class:`memex_dossier.fc.SparseVector` or
:class:`memex_dossier.fc.DenseVector`. If it isn't, a
:exc:`ValueError` is raised.
'''
ro = obj.constructor()
if name not in cbor_names_to_tags:
print(name)
raise ValueError(
'Unsupported feature type name: "%s". '
'Allowed feature type names: %r'
% (name, cbor_names_to_tags.keys()))
if not is_valid_feature_instance(ro):
raise ValueError(
'Constructor for "%s" returned "%r" which has an unknown '
'sub type "%r". (mro: %r). Object must be an instance of '
'one of the allowed types: %r'
% (name, ro, type(ro), type(ro).mro(), ALLOWED_FEATURE_TYPES))
self._registry[name] = {'obj': obj, 'ro': obj.constructor()}
self._inverse[obj.constructor] = name