Skip to content

Commit

Permalink
Fix from_dict() in the presence of optional datetime fields. (#329)
Browse files Browse the repository at this point in the history
  • Loading branch information
emosenkis authored Feb 3, 2022
1 parent eeddc84 commit 8c727d9
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 5 deletions.
7 changes: 3 additions & 4 deletions src/betterproto/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1180,8 +1180,8 @@ def from_dict(self: T, value: Dict[str, Any]) -> T:
if value[key] is not None:
if meta.proto_type == TYPE_MESSAGE:
v = getattr(self, field_name)
cls = self._betterproto.cls_by_field[field_name]
if isinstance(v, list):
cls = self._betterproto.cls_by_field[field_name]
if cls == datetime:
v = [isoparse(item) for item in value[key]]
elif cls == timedelta:
Expand All @@ -1191,16 +1191,15 @@ def from_dict(self: T, value: Dict[str, Any]) -> T:
]
else:
v = [cls().from_dict(item) for item in value[key]]
elif isinstance(v, datetime):
elif cls == datetime:
v = isoparse(value[key])
setattr(self, field_name, v)
elif isinstance(v, timedelta):
elif cls == timedelta:
v = timedelta(seconds=float(value[key][:-1]))
setattr(self, field_name, v)
elif meta.wraps:
setattr(self, field_name, value[key])
elif v is None:
cls = self._betterproto.cls_by_field[field_name]
setattr(self, field_name, cls().from_dict(value[key]))
else:
# NOTE: `from_dict` mutates the underlying message, so no
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@
},
"test6": "B",
"test7": "8589934592",
"test8": 2.5
"test8": 2.5,
"test9": "2022-01-24T12:12:42Z"
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
syntax = "proto3";

import "google/protobuf/timestamp.proto";

message InnerTest {
string test = 1;
}
Expand All @@ -13,6 +15,7 @@ message Test {
optional TestEnum test6 = 6;
optional uint64 test7 = 7;
optional float test8 = 8;
optional google.protobuf.Timestamp test9 = 9;
}

enum TestEnum {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,5 @@ def test_json(ref_json: str, obj_json: str) -> None:
"test6": None,
"test7": None,
"test8": None,
"test9": None,
}

0 comments on commit 8c727d9

Please sign in to comment.