将msgpackpython与嵌套的namedtuples一起使用

2024-04-29 05:05:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据结构如下:

user = UserTuple(
    name=u'Anakin', surname=u'Skywalker', birthdate=datetime.date(1981, 7, 25),
    profile=ProfileTuple(avatar=u'http://localhost/profile.jpg')
)

我想用msgpack python模块打包这些数据。但是msgpack将namedtuples转换为列表。像这样用msgpack打包数据并保留namedtuples是可能的,就像pickle/cpickle?在


Tags: 数据name数据结构datetimedatemsgpacksurnameprofile
2条回答

msgpack支持自定义对象打包和解包。 您只需要为命名元组创建方法。在

请参阅此处的文档: https://github.com/msgpack/msgpack-python#packingunpacking-of-custom-data-type

您需要有最新的msgpack-python版本。v0.4.7不起作用。(当前必须从主分支安装)。在

import msgpack
from collections import namedtuple

User = namedtuple('User', ['name', 'profile'])
Profile = namedtuple('Profile', ['avatar'])

def ext_pack(x):
    if isinstance(x, User):
        return msgpack.ExtType(1, msgpack.packb([x[0], x[1]], default=ext_pack, strict_types=True))
    elif isinstance(x, Profile):
        return msgpack.ExtType(2, msgpack.packb(x[0], default=ext_pack, strict_types=True))
    return x

def ext_unpack(code, data):
    if code == 1:
        name, profile = msgpack.unpackb(data, ext_hook=ext_unpack)
        return User(name, profile)
    elif code == 2:
        avatar = msgpack.unpackb(data, ext_hook=ext_unpack)
        return Profile(avatar)
    return msgpack.ExtType(code, data)

x = User("me", Profile(234))
s = msgpack.packb([x, [1, x]], default=ext_pack, strict_types=True)
msgpack.unpackb(s, ext_hook=ext_unpack)
>>> [User(name='me', profile=Profile(avatar=234)),
 [1, User(name='me', profile=Profile(avatar=234))]]

这里我们分别将UserProfile标记为类型代码1、2。或者,可以将所有namedtuple视为相同的类型代码,并将实际类型存储在数据字段中。在

相关问题 更多 >