Serializing custom types with msgpack in Autobahn

#1

Is there a preferred method for serializing custom types with msgpack, like Python dates/datetimes, in Autobahn?
I do it like this in my raw websocket code:

def default(obj):
    if isinstance(obj, datetime):
        return ExtType(1, obj.strftime("%Y%m%dT%H:%M:%S.%f"))
    if isinstance(obj, date):
        return ExtType(2, obj.strftime("%Y%m%d"))
    if isinstance(obj, Decimal):
        return ExtType(3, str(obj))
raise TypeError("Cannot serialize type %s" % obj.__class__.__name__)
def ext_hook(code, data):
    if code == 1:
        return datetime.strptime(data, "%Y%m%dT%H:%M:%S.%f")
    if code == 2:
        return datetime.strptime(data, "%Y%m%d").date()
    if code == 3:
        return Decimal(data)
    raise TypeError("Unknown type code %d" % code)

serialize = partial(packb, default=default, use_bin_type=True)
deserialize = partial(unpackb, encoding='utf-8', ext_hook=ext_hook)
0 Likes