【问题标题】:fastapi connection using Python requests使用 Python 请求的 fastapi 连接
【发布时间】:2021-06-11 20:06:49
【问题描述】:

我有一个用于简单 ML 模型的快速 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

如何解决?

【问题讨论】:

    标签: python rest scikit-learn fastapi


    【解决方案1】:

    FastAPI 需要这样的查询参数,但您在请求正文中发送 json。

    这需要一个查询参数

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

    您需要使用Body() 函数或 Pydantic 模型。

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

    【讨论】:

    猜你喜欢
    • 2021-03-14
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多