Skip to content

Commit

Permalink
works, debug
Browse files Browse the repository at this point in the history
  • Loading branch information
dphuang2 committed Nov 2, 2023
1 parent ff09d2d commit d1eb091
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,23 @@ def __eq__(self, other):
return self.__dict__ == other.__dict__


def handle_response(model: BaseModel):
T = typing.TypeVar('T', bound=BaseModel)


def construct_model_instance(model: typing.Type[T], data: dict) -> T:
"""
Since BaseModel#model_construct does not recursively construct models, we need to do it ourselves.
This is a recursive function that will construct the model and all of its child models.
Recursively construct an instance of a Pydantic model along with its nested models.
"""
pass
for field_name, field_type in model.__annotations__.items():
if field_name in data:
if typing_extensions.get_origin(field_type) is list:
list_item_type = typing_extensions.get_args(field_type)[0]
if issubclass(list_item_type, BaseModel):
data[field_name] = [construct_model_instance(list_item_type, item) for item in data[field_name]]
elif issubclass(field_type, BaseModel):
data[field_name] = construct_model_instance(field_type, data[field_name])

return model(**data)


class Dictionary(BaseModel):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ def fetch(
)
if validate:
return TestFetchResponsePydantic(**raw_response.body)
return TestFetchResponsePydantic.model_construct(**raw_response.body)
return api_client.construct_model_instance(TestFetchResponsePydantic, raw_response.body)


class ApiForget(BaseApi):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ class Fetch(BaseApi):
)
if validate:
return TestFetchResponsePydantic(**raw_response.body)
return TestFetchResponsePydantic.model_construct(**raw_response.body)
return api_client.construct_model_instance(TestFetchResponsePydantic, raw_response.body)


class ApiForget(BaseApi):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,6 @@ def test_recursively_convert_to_models(self):
self.assertIsNotNone(response.a.id)
self.assertIsNotNone(response.b[0].id)

def test_recursively_convert_to_models(self):
response = self.client.test.fetch()
self.assertIsNotNone(response.a.id)
self.assertIsNotNone(response.b[0].id)

def test_validate_recursively_converts(self):
response = self.client.test.fetch(validate=True)
self.assertIsNotNone(response.a.id)
Expand Down

0 comments on commit d1eb091

Please sign in to comment.