Python 枚举类的代码校验优化

class EventSortKey(Enum):
    create_time = "create_time"
    event_uuid = "event_uuid"


class SortOrder(Enum):
    asc = "asc"
    desc = "desc"


class EventQueryModel(BaseModel):
    keywords: Optional[list[str]]
    data_sources: Optional[list[int]]
    event_sources: Optional[list[int]]
    event_types: Optional[list[int]]
    event_start_time: datetime.datetime
    event_end_time: datetime.datetime
    event_regions: Optional[list[int]]  # todo: how to support this?
    event_related_orgs: Optional[list[int]]  # todo: how to support this?
    masked: Optional[bool] = True
    sort_key: Optional[list[str]] = Field(default=["create_time"])
    sort_order: Optional[list[str]] = Field(default=["asc"])

    class Config:
        orm_mode = True


    # @validator("sort_key")
    # def check_sort_key(cls, sort_key):
    #     if len(sort_key) != len(set(sort_key)):
    #         raise ValueError("The sort_key is not repeat")
    #     sort_key_list = [item.value for item in EventSortKey]
    #     intersection = set(sort_key) & set(sort_key_list)
    #     if len(sort_key) != len(intersection):
    #         raise ValueError("The sort_key is invalid")
    #     return sort_key


    @validator("sort_key")
    def check_sort_key(cls, sort_key):
        if len(sort_key) != len(set(sort_key)):
            raise ValueError("The sort_key is not repeat")
        _ = [EventSortKey(x) for x in sort_key]
        return sort_key


    # @validator("sort_order")
    # def check_sort_order(cls, sort_order):
    #     sort_order_list = [item.value for item in SortOrder]
    #     intersection = set(sort_order) & set(sort_order_list)
    #     if len(set(sort_order)) != len(intersection):
    #         raise ValueError("The sort_order is invalid")
    #     return sort_order


    @validator("sort_order")
    def check_sort_order(cls, sort_order):
        _ = [SortOrder(x) for x in sort_order]
        return sort_order


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值