覆盖FastAPI中jsonable_encode的默认编码器编码器、FastAPI、jsonable_encode

2023-09-03 11:23:56 作者:遺忘悲殇℃

我的代码类似于使用Fast API:

class EnumTestT(Enum):
    test_t_value = 0

object = { 
    test: test_t_value
}

enum_mapping = {
    test_t_value: "Test"
}

def enum_encoder(val: EnumTestT) -> str:
    return enum_mapping[val]

custom_encoder = {
    EnumTestT: enum_encoder
}

@app.get("/test")
async def test_get():
    return jsonable_encoder(object, custom_encoder=custom_encoder)

问题是jsonable_encoder在默认设置后应用自定义编码器。有没有办法在默认编码器之前应用它们。因为对于Enum和任何派生类,将报告枚举值而不是映射值。

推荐答案

在 Swift 5 中使用 JSON 和 Codable

FastAPI使用ENCODERS_BY_TYPE(来自pydanti.json)对一些基本数据类型进行编码。

ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
    bytes: lambda o: o.decode(),
    Color: str,
    datetime.date: isoformat,
    datetime.datetime: isoformat,
    datetime.time: isoformat,
    datetime.timedelta: lambda td: td.total_seconds(),
    Decimal: decimal_encoder,
    Enum: lambda o: o.value,

所以我要覆盖默认的日期时间编码,就像

 ENCODERS_BY_TYPE[datetime] = lambda date_obj: date_obj.strftime("%Y-%m-%d %H:%M:%S")