fastapi接口完整代码

可以看看官网教程

主要思路:安装fastapi、pydantic、uvicorn

撰写接口:用requests测试并调用

需要安装:

pip install fastapi pydantic uvicorn

主程序入口

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):  # 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):  # 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):  # 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):  # 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):  # 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=8900)

 调用:

# -*- coding: utf-8 -*-
import time

import requests



def test_data():
    url = 'https://h.shenlongip.com/index?from=seller&did=eUfuv6'
    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()

猜你喜欢

转载自blog.csdn.net/2301_77554343/article/details/134663727
今日推荐