Skip to content

Commit f3fb85a

Browse files
authored
fix(pydantic): add support for 'AwareDatetime' serialization (#4503)
Co-authored-by: MetaHG <25912337+MetaHG@users.noreply.github.com>
1 parent 4b90eb2 commit f3fb85a

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

litestar/plugins/pydantic/dto.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@
6868
pydantic_v2.IPvAnyAddress: str,
6969
pydantic_v2.IPvAnyInterface: str,
7070
pydantic_v2.IPvAnyNetwork: str,
71+
pydantic_v2.AwareDatetime: str,
7172
}
7273
)
7374

tests/unit/test_plugins/test_pydantic/test_dto.py

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
11
from __future__ import annotations
22

3+
from datetime import datetime, timezone
34
from typing import TYPE_CHECKING, Annotated, Optional, cast
45

56
import pydantic as pydantic_v2
67
import pytest
8+
from pydantic import AwareDatetime
79
from pydantic import v1 as pydantic_v1
810
from typing_extensions import Literal
911

1012
from litestar import Request, post
1113
from litestar.dto import DTOConfig
12-
from litestar.plugins.pydantic import PydanticDTO, _model_dump_json
14+
from litestar.plugins.pydantic import PydanticDTO, _model_dump, _model_dump_json
15+
from litestar.status_codes import HTTP_201_CREATED
1316
from litestar.testing import create_test_client
1417
from litestar.types import Empty
1518
from litestar.typing import FieldDefinition
@@ -23,6 +26,32 @@
2326
from litestar import Litestar
2427

2528

29+
def test_aware_datetime_serialization_v2(use_experimental_dto_backend: bool) -> None:
30+
class PydanticAwareDatetimeModel(pydantic_v2.BaseModel):
31+
tz_aware_datetime: AwareDatetime
32+
33+
class AwareDatetimeDTO(PydanticDTO[PydanticAwareDatetimeModel]):
34+
config = DTOConfig(experimental_codegen_backend=use_experimental_dto_backend)
35+
36+
@post(dto=AwareDatetimeDTO, signature_types=[PydanticAwareDatetimeModel])
37+
def handler(data: PydanticAwareDatetimeModel) -> PydanticAwareDatetimeModel:
38+
return data
39+
40+
with create_test_client(handler) as client:
41+
data = PydanticAwareDatetimeModel(tz_aware_datetime=datetime.now(tz=timezone.utc))
42+
dict_payload = _model_dump(data)
43+
json_payload = _model_dump_json(data)
44+
45+
headers = {"Content-Type": "application/json; charset=utf-8"}
46+
response = client.post(
47+
"/",
48+
content=json_payload,
49+
headers=headers,
50+
)
51+
assert response.status_code == HTTP_201_CREATED
52+
assert response.json() == dict_payload
53+
54+
2655
def test_schema_required_fields_with_pydantic_dto(
2756
use_experimental_dto_backend: bool, base_model: type[BaseModel]
2857
) -> None:

0 commit comments

Comments
 (0)