当前位置: 首页>>代码示例>>Python>>正文


Python cbor.loads方法代码示例

本文整理汇总了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
################################### 
开发者ID:becarpenter,项目名称:graspy,代码行数:19,代码来源:AskDNSSD.py

示例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 
开发者ID:fingon,项目名称:tfhfs,代码行数:19,代码来源:storage_lmdb.py

示例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) 
开发者ID:dossier,项目名称:memex-dossier-open,代码行数:19,代码来源:feature_collection.py

示例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 
开发者ID:hyperledger,项目名称:sawtooth-core,代码行数:24,代码来源:handler.py

示例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()) 
开发者ID:netsec-ethz,项目名称:pki,代码行数:20,代码来源:conf.py

示例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 
开发者ID:mediachain,项目名称:oldchain-client,代码行数:10,代码来源:utils.py

示例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
#################################### 
开发者ID:becarpenter,项目名称:graspy,代码行数:17,代码来源:GetDNSSD.py

示例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] 
开发者ID:becarpenter,项目名称:graspy,代码行数:28,代码来源:grasp.py

示例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 
开发者ID:fingon,项目名称:tfhfs,代码行数:5,代码来源:util.py

示例10: _loads

# 需要导入模块: import cbor [as 别名]
# 或者: from cbor import loads [as 别名]
def _loads(s):
    return json.loads(s, cls=_WAMPJsonDecoder) 
开发者ID:openstack,项目名称:deb-python-autobahn,代码行数:4,代码来源:serializer.py

示例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] 
开发者ID:openstack,项目名称:deb-python-autobahn,代码行数:35,代码来源:serializer.py

示例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 
开发者ID:dossier,项目名称:memex-dossier-open,代码行数:28,代码来源:ads.py

示例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) 
开发者ID:dossier,项目名称:memex-dossier-open,代码行数:11,代码来源:folder.py

示例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) 
开发者ID:dossier,项目名称:memex-dossier-open,代码行数:28,代码来源:feature_collection.py

示例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 
开发者ID:dossier,项目名称:memex-dossier-open,代码行数:38,代码来源:feature_collection.py


注:本文中的cbor.loads方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。