Browse Source

Merge 9ec5654d21 into 460f8d2cc8

pull/15476/merge
Vittoria Lanzo 12 hours ago
committed by GitHub
parent
commit
5c44e07862
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 14
      fastapi/encoders.py
  2. 3
      tests/test_jsonable_encoder.py

14
fastapi/encoders.py

@ -280,11 +280,13 @@ def jsonable_encoder(
return None
if isinstance(obj, dict):
encoded_dict = {}
allowed_keys = set(obj.keys())
if include is not None:
allowed_keys &= set(include)
if exclude is not None:
allowed_keys -= set(exclude)
allowed_keys: set[Any] | None = None
if include is not None or exclude is not None:
allowed_keys = set(obj.keys())
if include is not None:
allowed_keys &= set(include)
if exclude is not None:
allowed_keys -= set(exclude)
for key, value in obj.items():
if (
(
@ -293,7 +295,7 @@ def jsonable_encoder(
or (not key.startswith("_sa"))
)
and (value is not None or not exclude_none)
and key in allowed_keys
and (allowed_keys is None or key in allowed_keys)
):
encoded_key = jsonable_encoder(
key,

3
tests/test_jsonable_encoder.py

@ -82,6 +82,9 @@ def test_encode_dict():
"name": "Firulais",
"owner": {"name": "Foo"},
}
assert jsonable_encoder(pet, include={"name", "owner"}, exclude={"owner"}) == {
"name": "Firulais"
}
def test_encode_dict_include_exclude_list():

Loading…
Cancel
Save