Skip to content

Instantly share code, notes, and snippets.

@Gr1N
Last active June 29, 2017 11:32
Show Gist options
  • Save Gr1N/8e3775f25887dbcb1c544dae2b9d1f1a to your computer and use it in GitHub Desktop.
Save Gr1N/8e3775f25887dbcb1c544dae2b9d1f1a to your computer and use it in GitHub Desktop.
msgpack v2
import enum
import uuid
import arrow
import msgpack
@enum.unique
class Code(enum.IntEnum):
DATETIME_ISO8601 = 0
UUID = 1
def default(obj):
if isinstance(obj, arrow.Arrow):
return msgpack.ExtType(Code.DATETIME_ISO8601,
obj.isoformat().encode('utf-8'))
elif isinstance(obj, uuid.UUID):
return msgpack.ExtType(Code.UUID, obj.bytes)
raise TypeError(f'Unknown type: {obj!r}')
def ext_hook(code, data):
if code == Code.DATETIME_ISO8601:
return arrow.get(data.decode('utf-8'))
elif code == Code.UUID:
return uuid.UUID(bytes=data)
raise TypeError(f'Unknown type: code={code}; data={data}')
p = msgpack.packb({
'key1': 'string',
'key2': 2,
'key3': True,
'key4': {},
'key5': arrow.utcnow(),
'key6': b'bytes',
'key7': uuid.uuid4(),
}, default=default, use_bin_type=True)
print(p) # b'\x87\xa4key1\xa6string\xa4key2\x02\xa4key3\xc3\xa4key4\x80\xa4key5\xc7 \x002017-06-28T08:49:17.685105+00:00\xa4key6\xc4\x05bytes\xa4key7\xd8\x01S\xae\xbf\xbfD*E\xb8\xb7\x95\x86\xad\xff\xa8\xe4\xd4'
up = msgpack.unpackb(p, encoding='utf-8', ext_hook=ext_hook)
print(up) # {'key1': 'string', 'key2': 2, 'key3': True, 'key4': {}, 'key5': <Arrow [2017-06-28T08:49:17.685105+00:00]>, 'key6': b'bytes', 'key7': UUID('53aebfbf-442a-45b8-b795-86adffa8e4d4')}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment