From de52af9b82dc675b21c0a2f827585469e46c77ff Mon Sep 17 00:00:00 2001 From: Patrick Wang Date: Sat, 13 Jun 2020 13:20:11 -0400 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20When=20using=20Pydantic=20models=20?= =?UTF-8?q?with=20=5F=5Froot=5F=5F=20use=20the=20internal=20value=20in=20j?= =?UTF-8?q?sonable=5Fencoder=20(#1524)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/encoders.py | 2 ++ tests/test_jsonable_encoder.py | 9 +++++++++ 2 files changed, 11 insertions(+) diff --git a/fastapi/encoders.py b/fastapi/encoders.py index 26ceb21445f15..3f5b79d9ebbce 100644 --- a/fastapi/encoders.py +++ b/fastapi/encoders.py @@ -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, diff --git a/tests/test_jsonable_encoder.py b/tests/test_jsonable_encoder.py index adee443a8943c..d4ae3444211d8 100644 --- a/tests/test_jsonable_encoder.py +++ b/tests/test_jsonable_encoder.py @@ -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] ) @@ -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"