【问题标题】:Using msgpack-python with nested namedtuples使用带有嵌套命名元组的 msgpack-python
【发布时间】:2016-03-08 09:40:25
【问题描述】:

我的数据结构是这样的:

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 一样?

【问题讨论】:

    标签: python msgpack


    【解决方案1】:

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

    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 视为相同的类型代码,并将实际类型存储在数据字段中。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-06-01
        • 2021-09-07
        • 2015-09-15
        • 2017-11-18
        • 2013-09-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多