【Python3】FastAPI框架安装调试基操


FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.6+ 并基于标准的 Python 类型提示。

依赖

  Python3.6及更高版本

  • Starlette: 负责web部分
  • Pydantic: 负责数据部分

安装

  pip install fastapi

  需要一个ASGI服务器,生产环境可以使用Uvicorn 或者 Hypercorn

  pip install uvicorn

使用

 1 from typing import Optional
 2 
 3 from fastapi import FastAPI
 4 
 5 app = FastAPI()
 6 
 7 
 8 @app.get("/")
 9 def read_root():
10     return {"Hello": "World"}
11 
12 
13 @app.get("/items/{item_id}")
14 def read_item(item_id: int, q: Optional[str] = None):
15     return {"item_id": item_id, "q": q}

启动:uvicorn main:app --reload

uvicorn main:app 解释

  • main:main.py 文件(Python 模块)
  • app: 在main.py文件中通过app=FastAPI()创建的对象
  • --reload:让服务器在更新代码后重新启动,和Django/Flask/Tornado中DEBUG=True模式一样

访问:http://127.0.0.1:8000/items/1?q=wq  返回结果如下

{"item_id":1,"q":"wq"}

通过 / 和 /items/{item_id} 接收HTTP请求

以上路径都接受GET操作

/items/{item_id} 路径有一个路径参数item_id并且应该为int类型

/items/{item_id} 路径有个可选str类型的查询参数q

 

交互式API文档

http://127.0.0.1:8000/docs    会自动生成交互式API文档(由Swagger生成)

 

 「Try it out」按钮,之后你可以填写参数并直接调用 API:

 

 

可选API文档

访问: http://127.0.0.1:8000/redoc  (由ReDoc生成)

 

 

 

 菜鸟级入门FastAPI,还需小伙伴们自行搭建,多写多多练,此文仅供大家参考

good lucky !

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM