]> git.ipfire.org Git - thirdparty/fastapi/fastapi.git/commitdiff
✨ When using Pydantic models with __root__ use the internal value in jsonable_encoder...
authorPatrick Wang <patrick@covar.com>
Sat, 13 Jun 2020 17:20:11 +0000 (13:20 -0400)
committerGitHub <noreply@github.com>
Sat, 13 Jun 2020 17:20:11 +0000 (19:20 +0200)
fastapi/encoders.py
tests/test_jsonable_encoder.py

index 26ceb21445f158c943cf22197d98bd4d575f4323..3f5b79d9ebbceb974eacb8329ee6829393dc8bc3 100644 (file)
@@ -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,
index adee443a8943c52c5349d78b534ef24ff0cf54a6..d4ae3444211d8c3f7c4f2c08c813f0f128c37859 100644 (file)
@@ -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"