Skip to content

Commit

Permalink
Merge branch 'master' into fix/empty-reponse-body
Browse files Browse the repository at this point in the history
  • Loading branch information
tiangolo committed Sep 8, 2022
2 parents 834bb6d + c4007cb commit a942d46
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 3 deletions.
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Expand Up @@ -19,7 +19,7 @@ repos:
- --py3-plus
- --keep-runtime-typing
- repo: https://github.com/myint/autoflake
rev: v1.5.1
rev: v1.5.3
hooks:
- id: autoflake
args:
Expand All @@ -43,7 +43,7 @@ repos:
name: isort (pyi)
types: [pyi]
- repo: https://github.com/psf/black
rev: 22.6.0
rev: 22.8.0
hooks:
- id: black
ci:
Expand Down
2 changes: 2 additions & 0 deletions docs/en/docs/release-notes.md
Expand Up @@ -2,6 +2,8 @@

## Latest Changes

* ✨ Add support in `jsonable_encoder` for include and exclude with dataclasses. PR [#4923](https://github.com/tiangolo/fastapi/pull/4923) by [@DCsunset](https://github.com/DCsunset).
*[pre-commit.ci] pre-commit autoupdate. PR [#5352](https://github.com/tiangolo/fastapi/pull/5352) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).

## 0.82.0

Expand Down
6 changes: 5 additions & 1 deletion fastapi/encoders.py
Expand Up @@ -74,8 +74,12 @@ def jsonable_encoder(
obj_dict = dataclasses.asdict(obj)
return jsonable_encoder(
obj_dict,
exclude_none=exclude_none,
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

0 comments on commit a942d46

Please sign in to comment.