Skip to content

Commit c14fd70

Browse files
BrianXu0623Brian Xu
andauthored
Make message.to_dict() return bytes for DATA type field (#386)
* change to_dict return bytes for DATA type * reformat * reformat * add includes .h --------- Co-authored-by: Brian Xu <[email protected]>
1 parent a99ca72 commit c14fd70

File tree

3 files changed

+9
-1
lines changed

3 files changed

+9
-1
lines changed

capnp/lib/capnp.pyx

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1060,6 +1060,12 @@ cdef _to_dict(msg, bint verbose, bint ordered, bint encode_bytes_as_base64=False
10601060
# encode the message as base64 and return utf-8 string
10611061
return base64.b64encode(msg).decode('utf-8')
10621062

1063+
if msg_type is memoryview:
1064+
if encode_bytes_as_base64:
1065+
return base64.b64encode(bytes(msg)).decode('utf-8')
1066+
else:
1067+
return bytes(msg)
1068+
10631069
return msg
10641070

10651071

setup.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,7 @@ def run(self): # noqa: C901
222222
"*.capnp",
223223
"helpers/*.pxd",
224224
"helpers/*.h",
225+
"includes/*.h",
225226
"includes/*.pxd",
226227
"lib/*.pxd",
227228
"lib/*.py",

test/test_blob_to_dict_base64.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import os
22
import capnp
3+
import base64
34
import pytest
45

56
this_dir = os.path.dirname(__file__)
@@ -14,7 +15,7 @@ def test_blob_to_dict(blob_schema):
1415
blob_value = b"hello world"
1516
blob = blob_schema.BlobTest(blob=blob_value)
1617
blob_dict = blob.to_dict(encode_bytes_as_base64=True)
17-
assert blob_dict["blob"].tobytes() == blob_value
18+
assert base64.b64decode(blob_dict["blob"]) == blob_value
1819
msg = blob_schema.BlobTest.new_message()
1920
msg.from_dict(blob_dict)
2021
assert blob.blob == blob_value

0 commit comments

Comments
 (0)