How to use the msgpack.ExtType function in msgpack

To help you get started, we’ve selected a few msgpack examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github msgpack / msgpack-python / test / test_stricttype.py View on Github external
def default(o):
        if isinstance(o, tuple):
            # Convert to list and pack
            payload = packb(
                list(o), strict_types=True, use_bin_type=True, default=default
            )
            return ExtType(MSGPACK_EXT_TYPE_TUPLE, payload)
        raise TypeError(repr(o))
github msgpack / msgpack-python / test / test_unpack.py View on Github external
def __init__(self):
            super(MyUnpacker, self).__init__(ext_hook=self._hook, raw=False)

        def _hook(self, code, data):
            if code == 1:
                return int(data)
            else:
                return ExtType(code, data)

    unpacker = MyUnpacker()
    unpacker.feed(packb({"a": 1}))
    assert unpacker.unpack() == {"a": 1}
    unpacker.feed(packb({"a": ExtType(1, b"123")}))
    assert unpacker.unpack() == {"a": 123}
    unpacker.feed(packb({"a": ExtType(2, b"321")}))
    assert unpacker.unpack() == {"a": ExtType(2, b"321")}
github eventbrite / pysoa / pysoa / common / serializer / msgpack_serializer.py View on Github external
microseconds = int(seconds * 1000000.0)
            # Then pack it into a big-endian signed 64-bit integer.
            return msgpack.ExtType(
                ext_code,
                self.STRUCT_DATETIME.pack(microseconds),
            )
        elif isinstance(obj, datetime.date):
            # Serialize local-date objects by packing to a big-endian unsigned short and two big-endian unsigned chars.
            return msgpack.ExtType(
                self.EXT_DATE,
                self.STRUCT_DATE.pack(obj.year, obj.month, obj.day),
            )
        elif isinstance(obj, datetime.time):
            # Serialize dateless-time objects by packing to three big-endian unsigned chars and a big-endian unsigned
            # 32-bit integer.
            return msgpack.ExtType(
                self.EXT_TIME,
                self.STRUCT_TIME.pack(obj.hour, obj.minute, obj.second, obj.microsecond),
            )
        elif isinstance(obj, decimal.Decimal):
            obj_str = six.text_type(obj)[:65535].encode('utf-8')
            obj_len = len(obj_str)
            obj_encoder = struct.Struct(str('!H{}s'.format(obj_len)))
            return msgpack.ExtType(
                self.EXT_DECIMAL,
                obj_encoder.pack(obj_len, obj_str),
            )
        elif isinstance(obj, currint.Amount):
            # Serialize Amount objects. Start with the lowercased currency code as bytes.
            code = obj.currency.code.upper()
            if isinstance(code, six.text_type):
                code = code.encode('ascii')
github irmen / Pyro4 / src / Pyro4 / util.py View on Github external
if replacer:
            obj = replacer(obj)
        if isinstance(obj, set):
            return tuple(obj)  # msgpack module can't deal with sets so we make a tuple out of it
        if isinstance(obj, uuid.UUID):
            return str(obj)
        if isinstance(obj, bytearray):
            return bytes(obj)
        if isinstance(obj, complex):
            return msgpack.ExtType(0x30, struct.pack("dd", obj.real, obj.imag))
        if isinstance(obj, datetime.datetime):
            if obj.tzinfo:
                raise errors.SerializeError("msgpack cannot serialize datetime with timezone info")
            return msgpack.ExtType(0x32, struct.pack("d", obj.timestamp()))
        if isinstance(obj, datetime.date):
            return msgpack.ExtType(0x33, struct.pack("l", obj.toordinal()))
        if isinstance(obj, decimal.Decimal):
            return str(obj)
        if isinstance(obj, numbers.Number):
            return msgpack.ExtType(0x31, str(obj).encode("ascii"))     # long
        if isinstance(obj, array.array):
            if obj.typecode == 'c':
                return obj.tostring()
            if obj.typecode == 'u':
                return obj.tounicode()
            return obj.tolist()
        return self.class_to_dict(obj)
github codelv / enaml-native / android / app / src / main / assets / python / enamlnative / android / bridge.py View on Github external
def msgpack_encoder(sig, obj):
    """ When passing a JavaBridgeObject encode it in a special way so
        it can properly be interpreted as a reference.
    """
    if hasattr(obj, '__javaclass__'):
        return sig, msgpack.ExtType(ExtType.REF, msgpack.packb(obj.__id__))
    return sig, obj
github securestate / king-phisher / king_phisher / serializers.py View on Github external
def _msgpack_default(cls, obj):
		obj_type, obj_value = _serialize_ext_dump(obj)
		obj_type = next(i[0] for i in cls._ext_types.items() if i[1] == obj_type)
		if its.py_v3 and isinstance(obj_value, str):
			obj_value = obj_value.encode(cls.encoding)
		return msgpack.ExtType(obj_type, obj_value)
github eventbrite / pysoa / pysoa / common / serializer / msgpack_serializer.py View on Github external
)
        elif isinstance(obj, decimal.Decimal):
            obj_str = six.text_type(obj)[:65535].encode('utf-8')
            obj_len = len(obj_str)
            obj_encoder = struct.Struct(str('!H{}s'.format(obj_len)))
            return msgpack.ExtType(
                self.EXT_DECIMAL,
                obj_encoder.pack(obj_len, obj_str),
            )
        elif isinstance(obj, currint.Amount):
            # Serialize Amount objects. Start with the lowercased currency code as bytes.
            code = obj.currency.code.upper()
            if isinstance(code, six.text_type):
                code = code.encode('ascii')
            # Then pack it in with the minor value.
            return msgpack.ExtType(
                self.EXT_CURRINT,
                self.STRUCT_CURRINT.pack(code, obj.value),
            )

        # Wuh-woh
        raise TypeError('Cannot encode value of type {} to MessagePack: {}'.format(type(obj).__name__, obj))
github irmen / Pyro4 / src / Pyro4 / util.py View on Github external
def default(self, obj):
        replacer = self.__type_replacements.get(type(obj), None)
        if replacer:
            obj = replacer(obj)
        if isinstance(obj, set):
            return tuple(obj)  # msgpack module can't deal with sets so we make a tuple out of it
        if isinstance(obj, uuid.UUID):
            return str(obj)
        if isinstance(obj, bytearray):
            return bytes(obj)
        if isinstance(obj, complex):
            return msgpack.ExtType(0x30, struct.pack("dd", obj.real, obj.imag))
        if isinstance(obj, datetime.datetime):
            if obj.tzinfo:
                raise errors.SerializeError("msgpack cannot serialize datetime with timezone info")
            return msgpack.ExtType(0x32, struct.pack("d", obj.timestamp()))
        if isinstance(obj, datetime.date):
            return msgpack.ExtType(0x33, struct.pack("l", obj.toordinal()))
        if isinstance(obj, decimal.Decimal):
            return str(obj)
        if isinstance(obj, numbers.Number):
            return msgpack.ExtType(0x31, str(obj).encode("ascii"))     # long
        if isinstance(obj, array.array):
            if obj.typecode == 'c':
                return obj.tostring()
            if obj.typecode == 'u':
                return obj.tounicode()
            return obj.tolist()
        return self.class_to_dict(obj)
github roxma / vim-hug-neovim-rpc / pythonx / neovim_rpc_protocol.py View on Github external
def handler(obj):
        if type(obj) == BUFFER_TYPE:
            return msgpack.ExtType(BUFFER_TYPE_ID, msgpack.packb(obj.number))
        if type(obj) == WINDOW_TYPE:
            return msgpack.ExtType(WINDOW_TYPE_ID, msgpack.packb(obj.number))
        if type(obj) == vim.Function:
            try:
                return obj.name.encode()
            except Exception:
                return ""
        return obj
    return walk(handler, msg)
github fetchai / ledger-api-py / fetchai / ledger / api / common.py View on Github external
def _encode_msgpack_payload(cls, *args):
        items = []
        for value in args:
            if cls._is_primitive(value):
                items.append(value)
            elif isinstance(value, Address):
                items.append(msgpack.ExtType(77, bytes(value)))
            else:
                raise RuntimeError('Unknown item to pack: ' + value.__class__.__name__)
        return msgpack.packb(items)