【问题标题】:How to chain validations with pydantic如何使用 pydantic 链接验证
【发布时间】:2019-09-04 02:44:07
【问题描述】:

假设我有获取 json 数据的 webhook。这个json是由pydantic递归转换的。

@app.route("/", methods=['POST'])
async def telegram_webhook(request):
    update = Update.parse_obj(request.json)
    /* do something with update */

我检查这个 json 是 minimal 具有 Update 模型(内部包含 Message 模型)的有效对象:

class Update(BaseModel):
    update_id: int
    message: Message
    ...

class Message(BaseModel):
    message_id: int
    text: Optional[str]

但稍后在代码中我想扩展验证,所以要检查 message 不仅是 Message,而且是 TextMessage

// text field now is required
class TextMessage(Message):
    text: str

    @validator('text')
    def check_text_length(cls, value):
        length = len(value)
        if length > 4096:
            raise ValueError(f'text length {length} is too large')
        return value

所以我将消息传递给验证函数

def process_text_message(message):
    text_message = TextMessage.parse_obj(message)

但我得到的错误是 pydantic 不需要 Message 类型,而是 dict

我该怎么做? 如何对已验证(基本上)的数据应用额外验证?

【问题讨论】:

    标签: python json validation pydantic


    【解决方案1】:

    简短的回答是:使用message.dict():

    def process_text_message(message):
        text_message = TextMessage.parse_obj(message.dict())
    

    更长的答案是 parse_obj 应该被修复以应对“类似字典”的东西而不仅仅是字典,我将在 the issues you created 上解释这一点。

    【讨论】:

      猜你喜欢
      • 2014-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      • 2011-02-02
      • 1970-01-01
      • 2021-04-04
      相关资源
      最近更新 更多