将Pydantic模型转换为Dict是否无效



我有一项任务,必须将餐厅时间表转换为可读格式。我的实现是这样的:我的pydantic模型:

class DayValue(BaseModel):
type: Literal["open", "close"]
value: int = Field(gt=0, le=86399)

class RestaurantSchedule(BaseModel):
monday: List[Optional[DayValue]]
tuesday: List[Optional[DayValue]]
wednesday: List[Optional[DayValue]]
thursday: List[Optional[DayValue]]
friday: List[Optional[DayValue]]
saturday: List[Optional[DayValue]]
sunday: List[Optional[DayValue]]

API调用:

@app.route('/restaurant_schedule', methods=['POST'])
@validate()
def restaurant_schedule(body: RestaurantSchedule):
restaurant_schedule_dict = body.dict()
transformed_scheduled = transform_schedule(restaurant_schedule_dict)
print(transformed_scheduled)
return 

我的逻辑功能:

def transform_schedule(restaurant_schedules: Dict[str, Any]) -> Dict[str, str]:
opening_schedule = None
opening_day = None
closing_week_schedule = None
final_schedule: dict = {}
for day in days:
final_schedule[day] = []
for schedule in restaurant_schedules[day]:
if schedule['type'] == 'open':
opening_schedule = datetime.utcfromtimestamp(schedule['value']).strftime('%-I %p')
opening_day = day
else:
closing_schedule = datetime.utcfromtimestamp(schedule['value']).strftime('%-I %p')
if opening_schedule is not None:
final_schedule[opening_day].append(f'{opening_schedule} - {closing_schedule}')
else:
closing_week_schedule = closing_schedule
if closing_week_schedule:
final_schedule[days[6]].append(f'{opening_schedule} - {closing_week_schedule}')
return final_schedule

因此,样本输入请求为:

{
"monday": [],
"tuesday": [
{
"type": "open",
"value": 36000
},
{
"type": "close",
"value": 64800
}
],
.....
.....
}

预期响应为:

Monday: Closed
Tuesday: 10 AM - 6 PM
.....
.....

所以,它工作得很好,但我得到的反馈是:

在传递给逻辑函数时,已验证的模式模型被转换为dict,而不是使用模型本身,从而失去了所有类型优势。此外,逻辑函数还返回dict,使其失去所有的打字优势。

现在,我想知道将模型转换为dict是否不好?如果是,那么我如何改进我的实现以坚持最佳实践?

由于您使用的是fastapi和pydantic,因此不需要使用模型作为路由的入口并将其转换为dict。

将模型作为入口可以让您处理对象,而不是ditc/json 的参数

对象参数示例:

for mon in RestaurantSchedule.monday:
print(mon)

这意味着你必须在transform_schedule中以RestaurantSchedule作为条目来制定所有逻辑。不需要转换为dict。

此外,您应该从您的路线返回另一个模型,请参见此。

你可能会问,为什么要有一个入口模型和一个输出模型?这不是太夸张了吗?

通过这样做,您可以让fastapi生成一个swagger,准确地显示路由的输出和条目。让前端开发的工作更轻松

此外,对于作为后端开发人员的您来说,它允许您非常容易地实现TDD,对您输出的数据有更清晰的视图

最新更新