我正在尝试使用FastAPI服务神经网络。
from fastapi import Depends, FastAPI
from pydantic import BaseModel
from typing import Dict
class iRequest(BaseModel):
arg1: str
arg2: str
class iResponse(BaseModel):
pred: str
probs: Dict[str, float]
@app.post("/predict", response_model=iResponse)
def predict(request: iRequest, model: Model = Depends(get_model)):
pred, probs = model.predict(request.arg1, request.arg2)
return iResponse(pred = pred, probs = probs)
手动站点http://localhost:8000/docs#/default/predict_predict_post工作正常,并转换为以下curl命令:
curl -X POST "http://localhost:8000/predict" -H "accept: application/json" -H "Content-Type: application/json" -d "{"arg1":"I am the King","arg2":"You are not my King"}"
也可以。当我尝试使用python请求查询API时:
import requests
data = {"arg1": "I am the King",
"arg2": "You are not my King"}
r = requests.post("http://localhost:8000/predict", data=data)
我只得到"422不可处理的实体";错误。我哪里出错了?
您提供data
参数给requests.post
,它与Content-Type: application/x-www-form-urlencoded
进行POST,这不是JSON。
考虑使用requests.post(url, json=data)
,您应该没问题。