• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python umsgpack.packb函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: test_invalid_peer_type

    def test_invalid_peer_type(self):
        created = base.create(self.btctxstore, self.wif, "peers", None)

        # repack to eliminate namedtuples and simulate io
        repacked = umsgpack.unpackb(umsgpack.packb(created))

        self.assertIsNone(peers.read(self.btctxstore, repacked))
开发者ID:bookchin,项目名称:storjnode,代码行数:7,代码来源:peers.py


示例17: build_delay_message

    def build_delay_message(self,
                            task_id: str = None,
                            function_name: str = None,
                            args: List[str] = None,
                            kwargs: Dict = None) -> str:
        """
        If values are not specified, it will be taken from class atributes
        
        :return: message as a string 
        :rtype: str
        """
        if task_id is None:
            task_id = uuid.uuid4().hex

        if function_name is None:
            function_name = self.function_name

        if args is None:
            args = self.args

        if kwargs is None:
            kwargs = self.kwargs

        return msgpack.packb(
            dict(task_id=task_id,
                 function=function_name,
                 args=args,
                 kwargs=kwargs),
            use_bin_type=True)
开发者ID:Tolmachofof,项目名称:aiotasks,代码行数:29,代码来源:context.py


示例18: srvc_ask

def srvc_ask(identity, address, message):
    identity = '{}{}'.format('id_', identity)
    address = address
    pack_msg = umsgpack.packb(message)
    context, socket = setup_ask_socket(address, identity)
    log.debug('Client %s started\n' % identity)
    poll = zmq.Poller()
    poll.register(socket, zmq.POLLIN)

    socket.send(pack_msg)
    log.debug('Req from client %s sent.\n' % identity)

    response = None
    received_reply = False
    while not received_reply:
        sockets = dict(poll.poll(1000))
        if socket in sockets:
            if sockets[socket] == zmq.POLLIN:
                response = socket.recv()
                log.debug('Client %s received reply: %s\n' % (identity, response))
                received_reply = True

    socket.close()
    context.term()
    return response
开发者ID:outcastgeek,项目名称:pyramid_and_zmq_on_docker,代码行数:25,代码来源:srvc_client.py


示例19: trigger_all

 def trigger_all(self, function, parameter):
     packed = umsgpack.packb(parameter)
     err = tvio_input_trigger_all(self._input,
                                  c_char_p(function.encode("ascii")),
                                  packed,
                                  len(packed))
     _check_error(err)
开发者ID:ThingiverseIO,项目名称:pythingiverseio,代码行数:7,代码来源:input.py


示例20: _sendResponse

 def _sendResponse(self, response, msgID, address):
     if self.noisy:
         log.msg("sending response for msg id %s to %s" % (b64encode(msgID), address))
     timeout = reactor.callLater(self._waitTimeout, self._removeStaleId, msgID)
     txdata = '\x01%s%s' % (msgID, umsgpack.packb(response))
     self._outstanding[msgID] = (txdata, timeout)
     self.transport.write(txdata, address)
开发者ID:muraj,项目名称:rpcudp,代码行数:7,代码来源:protocol.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python umsgpack.unpackb函数代码示例发布时间:2022-05-27
下一篇:
Python log.debug函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap