| 1 |
from datetime import datetime, timezone |
| 2 |
|
| 3 |
from fastapi import FastAPI |
| 4 |
from fastapi.testclient import TestClient |
| 5 |
from pydantic import BaseModel |
| 6 |
|
| 7 |
|
| 8 |
def test_pydanticv2(): |
| 9 |
from pydantic import field_serializer |
| 10 |
|
| 11 |
class ModelWithDatetimeField(BaseModel): |
| 12 |
dt_field: datetime |
| 13 |
|
| 14 |
@field_serializer("dt_field") |
| 15 |
def serialize_datetime(self, dt_field: datetime): |
| 16 |
return dt_field.replace(microsecond=0, tzinfo=timezone.utc).isoformat() |
| 17 |
|
| 18 |
app = FastAPI() |
| 19 |
model = ModelWithDatetimeField(dt_field=datetime(2019, 1, 1, 8)) |
| 20 |
|
| 21 |
@app.get("/model", response_model=ModelWithDatetimeField) |
| 22 |
def get_model(): |
| 23 |
return model |
| 24 |
|
| 25 |
client = TestClient(app) |
| 26 |
with client: |
| 27 |
response = client.get("/model") |
| 28 |
assert response.json() == {"dt_field": "2019-01-01T08:00:00+00:00"} |