FastAPI GET请求报错value is not a valid list,移除响应模型正常
FastAPI GET请求使用response_model时报错
value is not a valid list的原因及解决办法 问题详情
在FastAPI的GET请求中设置response_model=List[schemas.ShowBlog]时,出现错误提示:value is not a valid list (type=type_error.list),但移除response_model后就能正常运行。相关代码如下:
路由代码
@router.get('/ads', response_model=List[schemas.ShowBlog]) def all_publish_blog(db: Session = Depends(get_db)): blogs = db.query(models.Blog).filter(models.Blog.is_published==True).all() if blogs: return { "blogs":blogs } else: raise HTTPException(400, detail=f'din\'t find any published ads')
模型代码
class ShowBlog(BaseModel): title: str body: str slug: str image_url: str ads_published_date: datetime ads_last_update_date: Optional[datetime] = ... ads_comment: Optional[str] = ... users_bp: ShowUser class Config(): orm_mode = True
报错原因
你设置的response_model=List[schemas.ShowBlog]明确要求接口返回由ShowBlog对象组成的列表,但实际返回的是一个包含blogs键的字典{"blogs": blogs},数据类型和响应模型的预期完全不匹配,因此FastAPI触发了类型校验错误。
解决办法
有两种可行的修复方案,根据你的返回格式需求选择:
方案1:保持返回字典格式,修改响应模型
如果需要继续返回{"blogs": 列表}这种字典结构,需要定义一个包含列表字段的新Pydantic模型:
# 在schemas中新增模型 class BlogListResponse(BaseModel): blogs: List[ShowBlog] class Config(): orm_mode = True
然后修改路由的response_model为这个新模型:
@router.get('/ads', response_model=schemas.BlogListResponse) def all_publish_blog(db: Session = Depends(get_db)): blogs = db.query(models.Blog).filter(models.Blog.is_published==True).all() if blogs: return { "blogs":blogs } else: raise HTTPException(400, detail=f'din\'t find any published ads')
方案2:直接返回列表,调整返回值
如果不需要外层字典,直接返回查询到的博客列表即可,同时建议将异常状态码改为404(更符合资源未找到的REST规范):
@router.get('/ads', response_model=List[schemas.ShowBlog]) def all_publish_blog(db: Session = Depends(get_db)): blogs = db.query(models.Blog).filter(models.Blog.is_published==True).all() if not blogs: raise HTTPException(404, detail=f'didn\'t find any published ads') return blogs
内容的提问来源于stack exchange,提问作者hawaj
相关产品推荐
相关产品推荐

