据说是一个非常好用,并且速度非常快的web接口提供程序。
参考:https://juejin.im/post/5e246f125188254c3c2758eb
官网:https://fastapi.tiangolo.com/
准备
Python 3.6+
pip install fastapi uvicorn
运行,修改代码会自动重启,发布的时候就不要—reload了。
uvicorn main:app --reload --host 0.0.0.0 --port 80
示例
from fastapi import FastAPI
from pydantic import BaseModel # 参数校验
app = FastAPI()
@app.get("/")
def index():
return {"message": "你已经正确创建api"}
# http://localhost:8000/query?uid=1
@app.get("/query")
def query(uid):
msg = f'uid为{uid}'
return {'success': True, 'msg': msg}
# http://localhost:8000/query/1 参数类型有校验
@app.get("/query/{uid}")
def query(uid: int):
msg = f'uid为{uid}'
return {'success': True, 'msg': msg}
class People(BaseModel):
name: str
age: int
address: str
salary: float
# jsonbody请求
@app.post("/insert")
def insert(people: People):
msg = f"名字:{people.name},年龄{people.age}"
return msg
import time
from fastapi import FastAPI, Request
app = FastAPI()
# 拦截器
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
API文档
有自动生成的接口文档,可以直接测试,简直……