我的@ router.post是这样的:
@router.post("/filter/filtering")
async def filter_test(skip: int = 0, limit: int = 100, company_name: str = None, db: Session = Depends(get_db)):
_audits = crud.filter_test(db, company_name)
return Response(status="Ok", code="200", message="Success fetch all data", result=_audits)
从crud.py可知,filter_test函数为:
def filter_test(db: Session, company_name: str = None):
# if company_name:
return db.query(Audit).filter(Audit.company_name == company_name).all()
当我用“company_name”作为key,“panda”作为value的参数发布请求时,它给出了正确的答案。但是当我尝试以Body格式发布请求时,它失败了。
带参数输出:
{
"code": "200",
"status": "Ok",
"message": "Success fetch all data",
"result": [
{
"product_name": "dondurma",
"audit_date": "2022-06-06T00:00:00",
"request_date": "2022-11-14T18:11:29.450855",
"correct_company_name": null,
"company_name": "panda",
"image_link": "www.test.com",
"id": 5,
"correct_name": null,
"correction_date": null
},
{
"product_name": "dondurma1",
"audit_date": "2022-06-06T00:00:00",
"request_date": "2022-11-14T18:40:18.925370",
"correct_company_name": null,
"company_name": "panda",
"image_link": "www.test.com",
"id": 6,
"correct_name": null,
"correction_date": null
},
{
"product_name": "dondurma1",
"audit_date": "2022-06-06T00:00:00",
"request_date": "2022-11-14T18:40:18.925370",
"correct_company_name": null,
"company_name": "panda",
"image_link": "www.test.com",
"id": 7,
"correct_name": null,
"correction_date": null
}
]
}
下面是我的JSON BODY格式:
{
"parameter":{
"company_name":"panda"
}
}
下面是JSON正文格式的输出:
{
"code": "200",
"status": "Ok",
"message": "Success fetch all data",
"result": [
{
"product_name": "dondurma1",
"audit_date": "2022-06-06T00:00:00",
"request_date": "2022-11-14T18:40:18.925370",
"correct_company_name": "kratos",
"company_name": null,
"image_link": "www.test.com",
"id": 8,
"correct_name": "kratos",
"correction_date": null
}
]
}
可能是什么问题呢?提前感谢
尝试使用params,它工作正常,但对于json主体格式,它失败了。postman的屏幕截图如下:
1条答案
按热度按时间0md85ypi1#
您要么需要定义一个pydantic模型作为主体,要么使用
Body
,因为您只接受一个值:这将用于传递
{}
、{"company_name": null}
或{"company_name": "foo"}
的请求主体-前两种情况下,company_name
变量将默认为None。如果你的例子中的
Response
是一个fastAPIResponse
,那么它对我来说就不起作用了,这是你的一个自定义类吗?这里我只是返回一个字典,如果它是json可序列化的,那么它就可以很好地工作。您可以考虑从该dict中删除状态和代码,因为框架已经默认返回HTTP状态200(即不是主体的一部分),或者您可以通过返回
JSONResponse
来传递自定义status_code。