写Python API好简单,非Gen

文件名称 版本号 作者 qq 版本
写Python API好简单,非Gen v1.0.0 学生宫布 8416837 Python 3.8
FastAPI (0.1.0)

FastAPI

Demo

  • 这里假设你已经会使用一款IDE(集成开发环境)或命令行

依赖

  • 安装依赖
    用的工具可能是pip|pip3
    执行pip3 --help试一下。
    在这里插入图片描述
    如果以下安装太慢,请使用国内镜像。
pip3 install fastapi
# ASGI 服务:uvicorn:
pip3 install uvicorn

代码

  • 主类 main.py
from fastapi import FastAPI

app = FastAPI()


@app.get("/{name}")
def read_root(name):
    return {"Hello": "World" + name}


@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

启动

命令行启动项目

uvicorn main:app --reload

【注意】IDE执行上述命令可能因配置问题而闪退
启动成功:
在这里插入图片描述

调用

  • 接口1
    localhost:8000/_name
    在这里插入图片描述
  • 接口2
    localhost:8000/items/3001?q=狗
    在这里插入图片描述

文档

  • FastAPI自带文档,地址是http://localhost:8000/docs
    在这里插入图片描述
  • 同时自带redoc文档,访问地址是http://localhost:8000/redoc
    *

炫技

参数验证

Json参数的接口
  • 代码比上述代码复杂一点点
  • 服务端:
from pydantic import BaseModel

from fastapi import FastAPI

app = FastAPI()


class Dog(BaseModel):
    nick_name: str
    tooth: int
    sex: int
    age_month: float


@app.post("/dog")
def read_item(dog: Dog):
    print(dog)
    return dog
  • 客户端:
    HTTPClient传json参数,以期获得响应参数
import requests

url = "http://localhost:8000/dog"

params = {"nick_name":"QWo","sex":1,"tooth":34, "age_month": 13.5}

res =  requests.post(url,json=params)

res.json()

执行请求,响应没问题:
在这里插入图片描述

测试功能
  • 框架底层做了封装,使用Python HTTPClient随手测试一下
import requests

url = "http://localhost:8000/dog"

params = {"nick_name":"QWo","sex":1,"tooth":"99"}

res =  requests.post(url,json=params)

res.json()

猜你喜欢

转载自blog.csdn.net/cc007cc009/article/details/106460217