【问题标题】:Is converting Pydantic model to Dict not efficient?将 Pydantic 模型转换为 Dict 效率不高吗?
【发布时间】:2021-12-28 00:50:22
【问题描述】:

我有一个任务,我必须将餐厅时间表转换为人类可读的格式。这就是我的实现的样子: 我的 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 不好?如果是,那么我该如何改进我的实施以坚持最佳实践?

【问题讨论】:

    标签: python flask python-typing pydantic python-dataclasses


    【解决方案1】:

    由于您使用的是 fastapi 和 pydantic,因此无需使用模型作为您的路线和 convert it to dict 的条目。

    将模型作为条目让您可以使用对象而不是 ditc/json 的参数

    对象参数示例:

    for mon in RestaurantSchedule.monday:
        print(mon)
    

    这意味着您必须在 transform_schedule 中创建所有逻辑,并将 RestaurantSchedule 作为条目。无需转换为 dict。

    另外,您应该从您的路线返回另一个模型,请参阅this

    您可能会问,为什么要有一个入口模型和一个输出模型?是不是太过分了?

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

    对于您作为后端开发人员,它可以让您非常轻松地实现 TDD,更清晰地查看您输出的数据

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-27
      • 2015-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-30
      • 1970-01-01
      • 2012-06-14
      相关资源
      最近更新 更多