From 1f21b16e03260d6935c73fa609b7017357abaf34 Mon Sep 17 00:00:00 2001 From: Carson Crane Date: Wed, 28 Jun 2023 09:39:10 -0700 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Add=20support=20for=20`deque`=20obj?= =?UTF-8?q?ects=20and=20children=20in=20`jsonable=5Fencoder`=20(#9433)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- fastapi/encoders.py | 4 ++-- tests/test_jsonable_encoder.py | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/fastapi/encoders.py b/fastapi/encoders.py index 2f95bcbf6..94f41bfa1 100644 --- a/fastapi/encoders.py +++ b/fastapi/encoders.py @@ -1,5 +1,5 @@ import dataclasses -from collections import defaultdict +from collections import defaultdict, deque from enum import Enum from pathlib import PurePath from types import GeneratorType @@ -124,7 +124,7 @@ def jsonable_encoder( ) encoded_dict[encoded_key] = encoded_value return encoded_dict - if isinstance(obj, (list, set, frozenset, GeneratorType, tuple)): + if isinstance(obj, (list, set, frozenset, GeneratorType, tuple, deque)): encoded_list = [] for item in obj: encoded_list.append( diff --git a/tests/test_jsonable_encoder.py b/tests/test_jsonable_encoder.py index f4fdcf601..1f43c33c7 100644 --- a/tests/test_jsonable_encoder.py +++ b/tests/test_jsonable_encoder.py @@ -1,3 +1,4 @@ +from collections import deque from dataclasses import dataclass from datetime import datetime, timezone from enum import Enum @@ -237,3 +238,12 @@ def test_encode_model_with_path(model_with_path): def test_encode_root(): model = ModelWithRoot(__root__="Foo") assert jsonable_encoder(model) == "Foo" + + +def test_encode_deque_encodes_child_models(): + class Model(BaseModel): + test: str + + dq = deque([Model(test="test")]) + + assert jsonable_encoder(dq)[0]["test"] == "test"