据说是一个非常好用,并且速度非常快的web接口提供程序。
参考:https://juejin.im/post/5e246f125188254c3c2758eb
官网:https://fastapi.tiangolo.com/

准备

Python 3.6+

  1. pip install fastapi uvicorn

运行,修改代码会自动重启,发布的时候就不要—reload了。

  1. uvicorn main:app --reload --host 0.0.0.0 --port 80

示例

  1. from fastapi import FastAPI
  2. from pydantic import BaseModel # 参数校验
  3. app = FastAPI()
  4. @app.get("/")
  5. def index():
  6. return {"message": "你已经正确创建api"}
  7. # http://localhost:8000/query?uid=1
  8. @app.get("/query")
  9. def query(uid):
  10. msg = f'uid为{uid}'
  11. return {'success': True, 'msg': msg}
  12. # http://localhost:8000/query/1 参数类型有校验
  13. @app.get("/query/{uid}")
  14. def query(uid: int):
  15. msg = f'uid为{uid}'
  16. return {'success': True, 'msg': msg}
  17. class People(BaseModel):
  18. name: str
  19. age: int
  20. address: str
  21. salary: float
  22. # jsonbody请求
  23. @app.post("/insert")
  24. def insert(people: People):
  25. msg = f"名字:{people.name},年龄{people.age}"
  26. return msg
  27. import time
  28. from fastapi import FastAPI, Request
  29. app = FastAPI()
  30. # 拦截器
  31. @app.middleware("http")
  32. async def add_process_time_header(request: Request, call_next):
  33. start_time = time.time()
  34. response = await call_next(request)
  35. process_time = time.time() - start_time
  36. response.headers["X-Process-Time"] = str(process_time)
  37. return response

API文档

有自动生成的接口文档,可以直接测试,简直……

http://localhost:8000/docs#/

image.png