簡體   English   中英

使用 Python 請求的 fastapi 連接

[英]fastapi connection using Python requests

我有一個用於簡單 ML model 的快速 api。 API 的發布請求是

@app.post('/predict')   
def predict_species(data: str):
    data_new = np.array([data])

    prob = lr_tfidf.predict_proba(data_new).max()
    pred = lr_tfidf.predict(data_new)
    return {'Movie Review': data,
             'Predictions':f'{pred[0]}',
            'Surity for Review': f'{prob}'}

現在,當我嘗試使用 python requests模塊連接它時,它給了我錯誤。

import requests

review = {'data': 'THIS IS A POSITIVE MOVIE'}
resp = requests.post("http://localhost:8000/predict", json=review)   

print(resp.content)

內容是

b'{"detail":[{"loc":["query","data"],"msg":"field required","type":"value_error.missing"}]}'

終端錯誤消息是

INFO:     127.0.0.1:45730 - "POST /predict HTTP/1.1" 422 Unprocessable Entity

如何解決這個問題?

FastAPI 需要這樣的查詢參數,但您在請求正文中發送 json。

這需要一個查詢參數

@app.post('/predict')   
def predict_species(data: str):

您需要使用Body() function 或 Pydantic model。

from fastapi import Body

@app.post('/predict')   
def predict_species(data: str = Body(...)):
    ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM