mirror of https://github.com/tiangolo/fastapi.git
✨ Add support in `jsonable_encoder` for include and exclude with dataclasses (#4923)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
This commit is contained in:
parent
895789bed0
commit
3ec498af63
|
|
@ -74,8 +74,12 @@ def jsonable_encoder(
|
||||||
obj_dict = dataclasses.asdict(obj)
|
obj_dict = dataclasses.asdict(obj)
|
||||||
return jsonable_encoder(
|
return jsonable_encoder(
|
||||||
obj_dict,
|
obj_dict,
|
||||||
exclude_none=exclude_none,
|
include=include,
|
||||||
|
exclude=exclude,
|
||||||
|
by_alias=by_alias,
|
||||||
|
exclude_unset=exclude_unset,
|
||||||
exclude_defaults=exclude_defaults,
|
exclude_defaults=exclude_defaults,
|
||||||
|
exclude_none=exclude_none,
|
||||||
custom_encoder=custom_encoder,
|
custom_encoder=custom_encoder,
|
||||||
sqlalchemy_safe=sqlalchemy_safe,
|
sqlalchemy_safe=sqlalchemy_safe,
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,4 @@
|
||||||
|
from dataclasses import dataclass
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
from pathlib import PurePath, PurePosixPath, PureWindowsPath
|
from pathlib import PurePath, PurePosixPath, PureWindowsPath
|
||||||
|
|
@ -19,6 +20,12 @@ class Pet:
|
||||||
self.name = name
|
self.name = name
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Item:
|
||||||
|
name: str
|
||||||
|
count: int
|
||||||
|
|
||||||
|
|
||||||
class DictablePerson(Person):
|
class DictablePerson(Person):
|
||||||
def __iter__(self):
|
def __iter__(self):
|
||||||
return ((k, v) for k, v in self.__dict__.items())
|
return ((k, v) for k, v in self.__dict__.items())
|
||||||
|
|
@ -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():
|
def test_encode_unsupported():
|
||||||
unserializable = Unserializable()
|
unserializable = Unserializable()
|
||||||
with pytest.raises(ValueError):
|
with pytest.raises(ValueError):
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue