如何修改Pydantic的GrammarSentence模型以适配空响应场景?
解决Pydantic模型适配无语法错误场景的方案
方案1:修改字段类型,允许列表包含None元素
直接调整corrected_sentences的类型定义,让它接受dict[str, str]或None的列表,这样API返回[None]时就不会触发验证错误。
from pydantic import BaseModel from typing import List, Dict class GrammarSentence(BaseModel): """ Model for the response containing a list of sentences with grammar mistake. """ corrected_sentences: List[Dict[str, str] | None]
方案2:用验证器自动处理None元素
如果希望返回的结构更统一(避免列表里出现None),可以添加Pydantic验证器,在数据验证前把列表中的None替换成空字典,或者直接过滤掉None。
替换None为空字典
from pydantic import BaseModel, validator from typing import List, Dict class GrammarSentence(BaseModel): """ Model for the response containing a list of sentences with grammar mistake. """ corrected_sentences: List[Dict[str, str]] @validator("corrected_sentences", pre=True) def replace_none_with_empty_dict(cls, value): return [item if item is not None else {} for item in value]
过滤None元素返回空列表
如果无语法错误时希望返回空列表而非带空元素的列表,修改验证器逻辑即可:
from pydantic import BaseModel, validator from typing import List, Dict class GrammarSentence(BaseModel): """ Model for the response containing a list of sentences with grammar mistake. """ corrected_sentences: List[Dict[str, str]] @validator("corrected_sentences", pre=True) def filter_out_none(cls, value): return [item for item in value if item is not None]
方案3:将[None]自动转换为空列表
如果业务上无错误时应该返回空列表,可以让验证器直接把[None]替换成[],同时给字段设置默认空列表:
from pydantic import BaseModel, validator from typing import List, Dict class GrammarSentence(BaseModel): """ Model for the response containing a list of sentences with grammar mistake. """ corrected_sentences: List[Dict[str, str]] = [] @validator("corrected_sentences", pre=True) def handle_none_list(cls, value): return [] if value == [None] else value
内容的提问来源于stack exchange,提问作者Jay Nair
相关产品推荐
相关产品推荐

