HTTPSPOST使用python请求查询FastAPI
我正在尝试使用 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 Unprocessable Entity”错误。我哪里出错了?
回答
您向 提供了一个data参数requests.post,它使用 进行 POST Content-Type: application/x-www-form-urlencoded,它不是 JSON。
考虑使用requests.post(url, json=data),你应该没问题。