RuntimeError: no validator found for <class 'elm.models.Warehouse'>, see…
- User
RuntimeError: no validator found for <class 'elm.models.Warehouse'>, see
arbitrary_types_allowedin Configdef _decode_warehouse(warehouse: Warehouse): return {"id": warehouse.id, "name": warehouse.name}
class TimeRatePackage(BaseModel): model_config = ConfigDict( arbitrary_types_allowed=True, json_encoders={Warehouse: _decode_warehouse}, )
- Assistant
The error message you're encountering suggests that the Pydantic model you're using does not know how to handle the custom type
Warehouse. To resolve this issue, you need to provide a way for Pydantic to understand how to serialize and deserialize this custom type.In your case, you are trying to define a custom JSON encoder for the
Warehouseclass. However, your implementation has a small mistake in setting up the configuration for the model. Here's a corrected version of your code:from pydantic import BaseModel, ConfigDict class Warehouse: def __init__(self, id: int, name: str): self.id = id self.name = name def _decode_warehouse(warehouse: Warehouse): return {"id": warehouse.id, "name": warehouse.name} class TimeRatePackage(BaseModel): model_config = ConfigDict( arbitrary_types_allowed=True, json_encoders={Warehouse: _decode_warehouse}, ) # Usage example warehouse = Warehouse(id=1, name="Warehouse A") time_rate_package = TimeRatePackage() serialized_data = time_rate_package.model_config.json_encoders[Warehouse](warehouse) print(serialized_data) - User
It fails in container attached to vscode,but when I run it individually in cmd line, it success
- Assistant
- User
vscode 连接进容器然后在postman执行
- Assistant
听起来你在使用VSCode连接到Docker容器中开发,然后通过Postman来测试API。然而,你在这种环境下遇到了与独立在命令行中运行时不同的问题。为了确保这两个环境的行为一致,请按照以下步骤进行排查和解决问题。
排查步骤
1. 确认Python和包版本一致
在VSCode容器终端和本地命令行中分别运行以下命令,确保Python和Pydantic等库的版本一致:
在容器中:
python --version pip freeze