Vittoria Lanzo 4 weeks 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 return None
if isinstance(obj, dict): if isinstance(obj, dict):
encoded_dict = {} encoded_dict = {}
allowed_keys = set(obj.keys()) allowed_keys: set[Any] | None = None
if include is not None: if include is not None or exclude is not None:
allowed_keys &= set(include) allowed_keys = set(obj.keys())
if exclude is not None: if include is not None:
allowed_keys -= set(exclude) allowed_keys &= set(include)
if exclude is not None:
allowed_keys -= set(exclude)
for key, value in obj.items(): for key, value in obj.items():
if ( if (
( (
@ -293,7 +295,7 @@ def jsonable_encoder(
or (not key.startswith("_sa")) or (not key.startswith("_sa"))
) )
and (value is not None or not exclude_none) 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( encoded_key = jsonable_encoder(
key, key,

3
tests/test_jsonable_encoder.py

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

Loading…
Cancel
Save