Skip to content

Commit

Permalink
Add CSV deserialization
Browse files Browse the repository at this point in the history
  • Loading branch information
faph committed Nov 1, 2023
1 parent 2839036 commit 8c7a21c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/py_adapter/plugin/_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,18 @@ def serialize(obj: py_adapter.Basic, stream: BinaryIO) -> BinaryIO:
stream.write(text_stream.read().encode("utf-8"))
stream.flush()
return stream


@py_adapter.plugin.hook
def deserialize(stream: BinaryIO) -> py_adapter.Basic:
"""
Deserialize CSV data as an object of basic Python types
:param stream: File-like object to deserialize
"""
import csv

text_stream = io.StringIO(stream.read().decode("utf-8"))
csv_reader = csv.DictReader(text_stream)
obj = next(csv_reader)
return obj
2 changes: 2 additions & 0 deletions tests/test_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,5 @@ def test_serialize_1_record(simple_ship):
data = py_adapter.serialize(simple_ship, format="CSV")
expected_lines = [b"name,build_on", b"Elvira,1970-12-31"]
assert data.splitlines() == expected_lines
obj_out = py_adapter.deserialize(data, SimpleShip, format="CSV")
assert obj_out == simple_ship

0 comments on commit 8c7a21c

Please sign in to comment.