Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ Add support in jsonable_encoder for include and exclude with dataclasses #4923

Merged
merged 4 commits into from Sep 8, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 6 additions & 3 deletions fastapi/encoders.py
Expand Up @@ -71,11 +71,14 @@ def jsonable_encoder(
sqlalchemy_safe=sqlalchemy_safe,
)
if dataclasses.is_dataclass(obj):
obj_dict = dataclasses.asdict(obj)
return jsonable_encoder(
obj_dict,
exclude_none=exclude_none,
dataclasses.asdict(obj),
include=include,
exclude=exclude,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
custom_encoder=custom_encoder,
sqlalchemy_safe=sqlalchemy_safe,
)
Expand Down
16 changes: 16 additions & 0 deletions tests/test_jsonable_encoder.py
@@ -1,3 +1,4 @@
from dataclasses import dataclass
from datetime import datetime, timezone
from enum import Enum
from pathlib import PurePath, PurePosixPath, PureWindowsPath
Expand All @@ -19,6 +20,12 @@ def __init__(self, owner: Person, name: str):
self.name = name


@dataclass
class Item:
name: str
count: int


class DictablePerson(Person):
def __iter__(self):
return ((k, v) for k, v in self.__dict__.items())
Expand Down Expand Up @@ -131,6 +138,15 @@ def test_encode_dictable():
}


def test_encode_dataclass():
item = Item(name="foo", count=100)
assert jsonable_encoder(item) == {"name": "foo", "count": 100}
assert jsonable_encoder(item, include={"name"}) == {"name": "foo"}
assert jsonable_encoder(item, exclude={"count"}) == {"name": "foo"}
assert jsonable_encoder(item, include={}) == {}
assert jsonable_encoder(item, exclude={}) == {"name": "foo", "count": 100}


def test_encode_unsupported():
unserializable = Unserializable()
with pytest.raises(ValueError):
Expand Down