fastapi

Форк
0
/
test_datetime_custom_encoder.py 
57 строк · 1.6 Кб
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
from .utils import needs_pydanticv1, needs_pydanticv2
8

9

10
@needs_pydanticv2
11
def test_pydanticv2():
12
    from pydantic import field_serializer
13

14
    class ModelWithDatetimeField(BaseModel):
15
        dt_field: datetime
16

17
        @field_serializer("dt_field")
18
        def serialize_datetime(self, dt_field: datetime):
19
            return dt_field.replace(microsecond=0, tzinfo=timezone.utc).isoformat()
20

21
    app = FastAPI()
22
    model = ModelWithDatetimeField(dt_field=datetime(2019, 1, 1, 8))
23

24
    @app.get("/model", response_model=ModelWithDatetimeField)
25
    def get_model():
26
        return model
27

28
    client = TestClient(app)
29
    with client:
30
        response = client.get("/model")
31
    assert response.json() == {"dt_field": "2019-01-01T08:00:00+00:00"}
32

33

34
# TODO: remove when deprecating Pydantic v1
35
@needs_pydanticv1
36
def test_pydanticv1():
37
    class ModelWithDatetimeField(BaseModel):
38
        dt_field: datetime
39

40
        class Config:
41
            json_encoders = {
42
                datetime: lambda dt: dt.replace(
43
                    microsecond=0, tzinfo=timezone.utc
44
                ).isoformat()
45
            }
46

47
    app = FastAPI()
48
    model = ModelWithDatetimeField(dt_field=datetime(2019, 1, 1, 8))
49

50
    @app.get("/model", response_model=ModelWithDatetimeField)
51
    def get_model():
52
        return model
53

54
    client = TestClient(app)
55
    with client:
56
        response = client.get("/model")
57
    assert response.json() == {"dt_field": "2019-01-01T08:00:00+00:00"}
58

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.