【python 算法接口】FastAPI如何编写POST请求部分

FastAPI 定义请求体,需要 Pydantic 模型。你需要从pydantic中导入BaseModel。

from pydantic import BaseModel

创建数据类型然后,声明你的数据模型为一个类,且该类继承 BaseModel.

# 创建数据模型
class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None

服务端完整demo:

# -*- coding: utf-8 -*-
# author:laidefa

# 载入包
import uvicorn
from fastapi import FastAPI
from f_cao_function import *
from pydantic import BaseModel


# 创建数据模型
class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None


app = FastAPI()


@app.get("/")
async  def root():
    return 'Hello World!'


@app.post("/sys/sinoma/v1/optimization/predict/fcao")
async def fcao_predict(item: Item):
    item_dict = item.dict()
    if item.tax:
        price_with_tax = item.price + item.tax
        item_dict.update({"price_with_tax": price_with_tax})
        return item_dict


if __name__ == '__main__':
    uvicorn.run(app)

客户端demo:

# -*- coding: utf-8 -*-
# author:laidefa

# 载入包
import requests
import json
import time

params={
    "name": "Foo",
    "description": "An optional description",
    "price": 45.2,
    "tax": 3.5
}


url='http://127.0.0.1:8000/sys/sinoma/v1/optimization/predict/fcao'

time1=time.time()
html = requests.post(url, json.dumps(params))
print('发送post数据请求成功!')
print('返回post结果如下:')
print(html.text)

time2=time.time()
print('总共耗时:' + str(time2 - time1) + 's')

运行结果如下:

发送post数据请求成功!
返回post结果如下:
{"name":"Foo","description":"An optional description","price":45.2,"tax":3.5,"price_with_tax":48.7}
总共耗时:0.004986763000488281s
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读