Browse Source

Add support for `deque` objects and children in `jsonable_encoder` (#9433)

Co-authored-by: Sebastián Ramírez <[email protected]>
pull/9319/merge
Carson Crane 2 years ago
committed by GitHub
parent
commit
1f21b16e03
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 4
      fastapi/encoders.py
  2. 10
      tests/test_jsonable_encoder.py

4
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(

10
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"

Loading…
Cancel
Save