Skip to content

Commit

Permalink
✨ When using Pydantic models with __root__ use the internal value in …
Browse files Browse the repository at this point in the history
…jsonable_encoder (#1524)
  • Loading branch information
Patrick Wang committed Jun 13, 2020
1 parent 748bedd commit 8fb7557
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
2 changes: 2 additions & 0 deletions fastapi/encoders.py
Expand Up @@ -71,6 +71,8 @@ def jsonable_encoder(
by_alias=by_alias,
skip_defaults=bool(exclude_unset or skip_defaults),
)
if "__root__" in obj_dict:
obj_dict = obj_dict["__root__"]
return jsonable_encoder(
obj_dict,
exclude_none=exclude_none,
Expand Down
9 changes: 9 additions & 0 deletions tests/test_jsonable_encoder.py
Expand Up @@ -76,6 +76,10 @@ class ModelWithDefault(BaseModel):
bla: str = "bla"


class ModelWithRoot(BaseModel):
__root__: str


@pytest.fixture(
name="model_with_path", params=[PurePath, PurePosixPath, PureWindowsPath]
)
Expand Down Expand Up @@ -158,3 +162,8 @@ def test_encode_model_with_path(model_with_path):
else:
expected = "/foo/bar"
assert jsonable_encoder(model_with_path) == {"path": expected}


def test_encode_root():
model = ModelWithRoot(__root__="Foo")
assert jsonable_encoder(model) == "Foo"

1 comment on commit 8fb7557

@github-actions
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.