# 必备安装包
pip install fastapi | |
pip install uvicorn |
# Overview 与铺垫资料
- https://www.runoob.com/flask/flask-tutorial.html
- https://www.runoob.com/flask/flask-basic-concept.html
- https://www.runoob.com/flask/flask-layout.html
Fastapi 基于 Flask,首先接触一下 Flask 的背景,同时了解路由、视图函数、请求对象和响应对象、模板文件、应用工厂、蓝图、配置对象、静态文件这些基本概念,以及了解 Flask 的项目结构如何。
# FastAPI 基础
- 初步了解: https://www.runoob.com/fastapi/fastapi-step1.html
- 了解 FastAPI 的路由:https://www.runoob.com/fastapi/fastapi-route.html
- 入门,获得整体的认知:https://zhuanlan.zhihu.com/p/131618992
于是自己手搓玩了一玩:
from fastapi import FastAPI | |
from pydantic import BaseModel | |
app = FastAPI() | |
@app.get("/") | |
async def read_root(): | |
return "Hello, Man! Please using item_id(free), q(your words for me) and open(True or False) to visit /items/." | |
@app.get("/items/") | |
async def read_item(item_id: int, q: str = None, open: str = "False"): | |
item = {"item_id": item_id} | |
if open == "True": | |
item["open"] = open | |
else: | |
item["description"] = "You can set open to True to see this description." | |
return item["description"] | |
if q: | |
item["myQ"] = f"Thanks for your words: {q}, but you are a foolish man!" | |
return item["myQ"] |
在浏览器打开 http://127.0.0.1:8000/items/?item_id=3&q=你好&open=True 会得到 Thanks for your words: 你好, but you are a foolish man! ,如果 open 不指定为 True,那么就会得到 You can set open to True to see this description.
- 了解一下交互式文档怎么打开,以后有更多内容可以往文档查:https://www.runoob.com/fastapi/fastapi-api-doc.html
- Pydantic 模型是 FastAPI 用的最多的模型库,主要用于数据的序列化和模型的验证,比较重要:https://www.runoob.com/fastapi/fastapi-pydantic.html
我对 Pydantic 模型的理解是,它允许程序员对数据以更加简便的方式包装成一个类,这个类会在进行 HTTP 请求和响应时,将数据转换为特定类型(例如 JSON)或反向序列化,而且这是自动的。看下面的代码:
from fastapi import FastAPI | |
from pydantic import BaseModel | |
app = FastAPI() | |
class Item(BaseModel): | |
name: str | |
description: str = None | |
price: float | |
tax: float = None | |
@app.post("/items/") | |
def create_item(item: Item): | |
return item |
如果传入的 item 参数是一个 JSON 格式的数据,可以看到 FastAPI 是用 Pydantic 模型接收这个数据的,Item 类的数据结构也特别像 JSON 的数据结构。
- 了解完 Pydantic 模型,可以更好地理解请求和响应这部分内容,进一步理解 Pydantic 模型在 FastAPI 的作用:https://www.runoob.com/fastapi/fastapi-request-response.html ,除此之外了解请求头 Header,Cookie 类型注解,重定向 RedirectResponse,异常 HTTPException 以及自定义响应头 JSONResponse。
- 学习 FastAPI 的依赖注入系统:https://www.runoob.com/fastapi/fastapi-path-operation-dependencies.html
我们见依赖这块的内容,有这样的代码:
from fastapi import Depends, FastAPI, HTTPException | |
app = FastAPI() | |
# 依赖项函数 | |
def common_parameters(q: str = None, skip: int = 0, limit: int = 100): | |
return {"q": q, "skip": skip, "limit": limit} | |
# 路由操作函数 | |
@app.get("/items/") | |
async def read_items(commons: dict = Depends(common_parameters)): | |
return commons | |
# 后处理函数 | |
async def after_request(): | |
# 这里可以执行一些后处理逻辑,比如记录日志 | |
pass | |
# 后处理依赖项 | |
@app.get("/items/", response_model=dict) | |
async def read_items_after(request: dict = Depends(after_request)): | |
return {"message": "Items returned successfully"} |
仔细一看,发现一个问题:为什么 after_request 函数被称为后处理函数,为什么 common_parameters 被称为依赖项函数(又叫预处理函数),而不是反过来?我目前的理解是代码顺序造成的,当访问 /items/ 路径时,会首先从上到下寻找 /items/ 的路由操作函数,于是第一个路由操作函数 read_items 首先响应,响应完后,再向后执行 /items/ 的路由操作函数,于是乎后面的称为后处理。
# 进阶
上面流程走完后算基本入门了,暂时够用,如果想进一步了解更多的基础知识,可以考虑下面的指南:
- 表单:https://www.runoob.com/fastapi/fastapi-form.html
- 进阶知识:https://www.runoob.com/fastapi/fastapi-core.html
- 除此之外还有如何在 VSCode 中使用 FastAPI 的技巧:https://www.runoob.com/fastapi/vscode-fastapi.html
最终最终会回归到 FastAPI 官方文档,这个才是最权威最全面的,开发基本离不开查手册,FastAPI 官网:https://fastapi.tiangolo.com/zh/
