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


Python umsgpack.packb函数代码示例

本文整理汇总了Python中umsgpack.packb函数的典型用法代码示例。如果您正苦于以下问题:Python packb函数的具体用法?Python packb怎么用?Python packb使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了packb函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_pack_exceptions

 def test_pack_exceptions(self):
     for (name, obj, exception) in pack_exception_test_vectors:
         obj_repr = repr(obj)
         print("\tTesting %s: object %s" % (name, obj_repr if len(obj_repr) < 24 else obj_repr[0:24] + "..."))
         try:
             umsgpack.packb(obj)
         except Exception as e:
             self.assertTrue(isinstance(e, exception))
开发者ID:cforger,项目名称:u-msgpack-python,代码行数:8,代码来源:test_umsgpack.py

示例2: test_pack_exceptions

    def test_pack_exceptions(self):
        for (name, obj, exception) in pack_exception_test_vectors:
            obj_repr = repr(obj)
            print("\tTesting %s: object %s" %
                  (name, obj_repr if len(obj_repr) < 24 else obj_repr[0:24] + "..."))

            with self.assertRaises(exception):
                umsgpack.packb(obj)
开发者ID:vsergeev,项目名称:u-msgpack-python,代码行数:8,代码来源:test_umsgpack.py

示例3: packet_send

def packet_send(string):
	random_id = hash(string) % 768 + randint(0, 256)	# get and ID by hashing the string
	packet_num = 1							# starting number (from data)
	for piece in [string[x:x+40] for x in range(0,len(string),40)]:			# divide string, create and send packets
		packet = {"id": random_id, "pn": packet_num, "dt": piece}			# compose data packet
		xbee.send("tx", dest_addr=XBEE_MESH_DESC, data=packb(packet))		# serialize and send
		packet_num += 1														# increase packet count
	packet = {"id": random_id, "pn": 0, "dt": packet_num}					# compose header packet
	xbee.send("tx", dest_addr=XBEE_MESH_DESC, data=packb(packet))			# serialize and send
开发者ID:luisbc92,项目名称:antenna,代码行数:9,代码来源:antenna.py

示例4: password_hash

def password_hash(word, salt=None, iterations=config.pbkdf2_iterations):
    if salt is None:
        salt = random.read(16)
    elif len(salt) > 16:
        _, salt, iterations = umsgpack.unpackb(salt)

    word = umsgpack.packb(word)

    rawhash = PBKDF2(word, salt, iterations).read(32)

    return umsgpack.packb([rawhash, salt, iterations])
开发者ID:Crooky,项目名称:qiandao,代码行数:11,代码来源:mcrypto.py

示例5: aes_encrypt

def aes_encrypt(word, key=config.aes_key, iv=None):
    if iv is None:
        iv = random.read(16)

    word = umsgpack.packb(word)
    mod = len(word) % 16
    if mod != 0:
        word += '\0' * (16-mod)

    aes = AES.new(key, AES.MODE_CBC, iv)
    ciphertext = aes.encrypt(word)

    return umsgpack.packb([ciphertext, iv])
开发者ID:Crooky,项目名称:qiandao,代码行数:13,代码来源:mcrypto.py

示例6: getToken

def getToken():
    print "Requesting Token"
    print ":".join("{0:x}".format(ord(c)) for c in umsgpack.packb(['T']))
    
    s.send(umsgpack.packb(['T']))
    token = umsgpack.unpackb(s.recv(1024))
    print "Token Recived:",token
    crc = token.pop()
    if struct.unpack('<H', crc)[0] == crc16.crc16(''.join(token)):
        print "Token Valid - CRC passed"
    else:
        print "Token INVALID", crc16.crc16(token[1]), struct.unpack('<H', crc)[0]
    
    return token[1]
开发者ID:HSBNE,项目名称:snarc_code,代码行数:14,代码来源:tester.py

示例7: _http_request_func

    def _http_request_func(self, path, payload):
        url_api = '%s%s' % (self.base_uri, path)
        http_headers = {
            'Content-Type': 'application/x-msgpack',
        }
        mp_payload = ''.join(map(chr, umsgpack.packb(payload)))

        try:
            pool = urllib3.PoolManager(timeout=3.0)
            req = pool.urlopen(
                'POST',
                url_api,
                headers=http_headers,
                body=mp_payload,
            )
            return json.loads(req.data.decode('utf-8'))

        except urllib3.exceptions.MaxRetryError:
            fallback = self._fallback  # or .... or ...

            if fallback:
                IkaUtils.dprint(
                    '%s: Remote API Error. Falling back to local mode' % self)
                return self._local_request_func(path, payload)

        raise Exception(
            'API Error: Failed to connect to API endpoint. (No fallback)')
开发者ID:clovervidia,项目名称:IkaLog,代码行数:27,代码来源:client.py

示例8: post_payload

    def post_payload(self, payload, api_key=None):
        if self.dry_run:
            IkaUtils.dprint(
                '%s: Dry-run mode, skipping POST to stat.ink.' % self)
            return

        url_statink_v1_battle = 'https://stat.ink/api/v1/battle'

        if api_key is None:
            api_key = self.api_key

        if api_key is None:
            raise('No API key specified')

        http_headers = {
            'Content-Type': 'application/x-msgpack',
        }

        # Payload data will be modified, so we copy it.
        # It is not deep copy, so only dict object is
        # duplicated.
        payload = payload.copy()
        payload['apikey'] = api_key
        mp_payload_bytes = umsgpack.packb(payload)
        mp_payload = ''.join(map(chr, mp_payload_bytes))

        pool = urllib3.PoolManager()
        req = pool.urlopen('POST', url_statink_v1_battle,
                           headers=http_headers,
                           body=mp_payload,
                           )

        if self.show_response_enabled:
            print(req.data.decode('utf-8'))
开发者ID:tkymsd,项目名称:IkaLog,代码行数:34,代码来源:statink.py

示例9: __non_len_string

    def __non_len_string(self):
        # type: (InternalMessage) -> bytes
        """Returns a :py:class:`bytes` object containing the entire message,
        excepting the total length header

        Raises:

            TypeError: If any of the arguments are not serializable. This
                        means your objects must be one of the following:

                        - :py:class:`bool`
                        - :py:class:`float`
                        - :py:class:`int` (if ``2**64 > x > -2**63``)
                        - :py:class:`str`
                        - :py:class:`bytes`
                        - :py:class:`unicode`
                        - :py:class:`tuple`
                        - :py:class:`list`
                        - :py:class:`dict` (if all keys are
                            :py:class:`unicode`)
        """
        if not self.__string:
            try:
                self.__string = packb(self.packets)
            except UnsupportedTypeException as e:
                raise TypeError(*e.args)
        return self.__string
开发者ID:gappleto97,项目名称:p2p-project,代码行数:27,代码来源:messages.py

示例10: run

    def run(self):
        """
        Continuously monitor the A/D
        :return:
        """
        value = None
        while True:
            try:
                for entry in self.pin_states:
                    if entry['enabled']:
                        if entry['mode'] == 'analog':
                            value = ADC.read(entry['pin'])
                            value = round(value, 4)

                        elif entry['mode'] == 'sonar':
                            value = ADC.read_raw(entry['pin'])
                            value = self.convert_to_distance(value)

                        digital_reply_msg = umsgpack.packb({u"command": "analog_read", u"pin": entry['pin'],
                                                            u"value": str(value)})

                        envelope = ("B" + self.board_num).encode()
                        self.publisher.send_multipart([envelope, digital_reply_msg])
                time.sleep(0.05)
            except KeyboardInterrupt:
                sys.exit(0)
开发者ID:MrYsLab,项目名称:xideco,代码行数:26,代码来源:xibb.py

示例11: test_message_serializer_deserialize_completion_response

def test_message_serializer_deserialize_completion_response():
    # TODO should start with a packed message and use msgpack to unpack, for now start with builtin form:
    unpacked = {
        '_message': 'CompletionResponse',
        'token': 'thetoken',
        'start': 11,
        'end': 12,
        'limitExceeded': True,
        'options': [
            {'insert': 'insert', 'desc': 'thedescription', 'semantics': 'string', 'extensionId': 'theExtId'},
            {'insert': 'insert2', 'desc': 'thedescription2', 'semantics': 'identifier', 'extensionId': 'theExtId2'}
        ]
    }

    packed = umsgpack.packb(unpacked)

    # and use serializer without unpacker:
    serializer = MessageSerializer()

    msg = serializer.deserialize(packed)

    expected = CompletionResponse(11, 12, True, [CompletionOption('insert', 'thedescription', semantics=SemanticType.string, extensionId='theExtId'),
                                                 CompletionOption('insert2', 'thedescription2', semantics=SemanticType.identifier, extensionId='theExtId2')],
                                  'thetoken')

    # avoid implementation of eq in schema classes, so rely on correct serialization for now:
    assert serializer.serialize(msg) == serializer.serialize(expected)
开发者ID:Nicoretti,项目名称:jep-python,代码行数:27,代码来源:test_protocol.py

示例12: report_i2c_data

    def report_i2c_data(self, data):
        # create a topic specific to the board number of this board
        envelope = ("B" + self.board_num).encode()

        msg = umsgpack.packb({u"command": "i2c_reply", u"board": self.board_num, u"data": data})

        self.publisher.send_multipart([envelope, msg])
开发者ID:MrYsLab,项目名称:xideco,代码行数:7,代码来源:xibbi2c.py

示例13: put_nowait

 def put_nowait(self, obj):
     if self.lazy_limit and self.last_qsize < self.maxsize:
         pass
     elif self.full():
         raise self.Full
     self.last_qsize = self.redis.rpush(self.name, umsgpack.packb(obj))
     return True
开发者ID:pangyemeng,项目名称:myjob,代码行数:7,代码来源:redis_queue.py

示例14: save_cache

 def save_cache(self):
     """Write current in-memory config to cache file."""
     LOG.info("Writing settings to cache file '%s'.", self.cache_file)
     with open(self.cache_file, "wb") as stream:
         dicts = [Subscription.Subscription.encode_subscription(s) for s in self.subscriptions]
         packed = umsgpack.packb(dicts)
         stream.write(packed)
开发者ID:andrewmichaud,项目名称:puckfetcher,代码行数:7,代码来源:config.py

示例15: process

 def process(self, message):
     datagram, host, port =  umsgpack.unpackb(message[0])
     reply = self.processAuth(datagram, host, port)
     logger.info("[Radiusd] :: Send radius response: %s" % repr(reply))
     if self.config.system.debug:
         logger.debug(reply.format_str())
     self.pusher.push(umsgpack.packb([reply.ReplyPacket(),host,port]))
开发者ID:niebaopeng,项目名称:ToughRADIUS,代码行数:7,代码来源:radiusd.py


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