1、摘要
本文主要讲解:fastapi写get和post接口并调用_用python直接启动 主要思路:
- 安装fastapi、pydantic、uvicorn
- 撰写接口
- 用requests测试并调用
2、相关技术
安装步骤
pip install fastapi pydantic uvicorn
最新的 Python web框架的性能响应排行版,fastapi排行老三
3、完整代码和步骤
主运行程序入口
import uvicorn
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
age: int
height: float
is_offer: bool = None
app = FastAPI()
@app.get("/{people_id}")
async def update_item(people_id: str, item: Item):
return {
"method": 'get',
"people_name": item.name,
"people_age": item.age,
"people_height": item.height,
'people': people_id
}
@app.put("/{people_id}")
async def update_item(people_id: str, item: Item):
return {
"method": 'put',
"people_name": item.name,
"people_age": item.age,
"people_height": item.height,
'people': people_id
}
@app.post("/{people_id}")
async def update_item(people_id: str, item: Item):
return {
"method": 'post',
"people_name": item.name,
"people_age": item.age,
"people_height": item.height,
'people': people_id
}
@app.post("/warp")
async def warp(people_id: str, item: Item):
return {
"method": 'post',
"people_name": item.name,
"people_age": item.age,
"people_height": item.height,
'people': people_id
}
@app.delete("/{people_id}")
async def update_item(people_id: str, item: Item):
return {
"method": 'delete',
"people_name": item.name,
"people_age": item.age,
"people_height": item.height,
'people': people_id
}
if __name__ == '__main__':
uvicorn.run(app=app, host="127.0.0.1", port=5200)
调用代码
import time
import requests
def test_data():
url = 'http://127.0.0.1:5200/warp'
print('测试url:', url)
for i in range(20000):
params = {"name": "20:00", "age": 12, "height": 1.2}
print(params)
print('方法:', 'post')
start_time = time.time()
dd = requests.post(url, json=params)
end_time = time.time()
print('返回:', dd.text)
print("运行时长:" + str((end_time - start_time)))
test_data()
4、学习链接
fastapi 的启动方式
fastapi——快速入门
(入门篇)Python框架之FastAPI——一个比Flask和Tornado更高性能的API 框架
|