FastAPI定义请求体,需要Pydantic模型。你需要从pydantic中导入BaseModel。
创建数据类型然后,声明你的数据模型为一个类,且该类继承BaseMode
# 创建数据模型
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
文章为作者独立观点,不代表股票交易接口观点