[英]How to inflect from snake case to camel case post the pydantic schema validations
[英]How to chain validations with pydantic
假設我有webhook,可在其中獲取json數據。 此json由pydantic遞歸轉換。
@app.route("/", methods=['POST'])
async def telegram_webhook(request):
update = Update.parse_obj(request.json)
/* do something with update */
我檢查此json是具有Update模型(內部包含Message模型)的最小有效對象:
class Update(BaseModel):
update_id: int
message: Message
...
class Message(BaseModel):
message_id: int
text: Optional[str]
但是稍后在代碼中,我想擴展驗證,因此要檢查消息不僅是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 。
我該怎么做? 我如何才能對已驗證(基本)的數據進行其他驗證?
簡短的答案是:使用message.dict()
:
def process_text_message(message):
text_message = TextMessage.parse_obj(message.dict())
更長的答案是應該固定parse_obj
以應對“ dict-like”之類的事情,而不僅僅是dict,我將在您創建的問題上對此進行解釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.