fastapi写get和post接口并调用_用python直接启动

1、摘要

本文主要讲解:fastapi写get和post接口并调用_用python直接启动
主要思路:

  1. 安装fastapi、pydantic、uvicorn
  2. 撰写接口
  3. 用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):  # 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=5200)

调用代码

# -*- coding: utf-8 -*-
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 框架

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值