FastAPI 学习
大约 3 分钟
FastAPI 学习
FastAPI 是一个用于构建API的现代、快速(高性能)的web框架,使用Python 3.6+并基于标准的Python类型提示。它具有如下这些优点:快速:可与NodeJS和Go比肩的极高性能(归功于Starlette和Pydantic);高效编码:提高功能开发速度约200%至300%;更少bug:减少约40%的人为(开发者)导致错误;智能:极佳的编辑器支持,处处皆可自动补全,减少调试时间;简单:设计的易于使用和学习,阅读文档的时间更短;简短:使代码重复最小化,通过不同的参数声明实现丰富功能;健壮:生产可用级别的代码。
安装
#安装fastapi
pip3 install fastapi
#安装AIGC服务器
pip3 install "uvicorn[standard]"
一个简单的例子:
from typing import Union
from fastapi import FastAPI
#创建一个 FastAPI「实例」
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}
运行
uvicorn main:app --reload
uvicorn main:app 命令含义
main:main.py 文件。
app:在 main.py 文件中通过 app = FastAPI() 创建的对象。
--reload:让服务器在更新代码后重新启动。仅在开发时使用该选项。
交互式 API 文档: http://127.0.0.1:8000/docs
FastAPI会生成自定义文档,可直接查看api接口和接受的参数属性。
路径参数
from fastapi import FastAPI
app = FastAPI()
# 使用与 python 格式化字符串相同的语法来声明路径的参数
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
# 路径参数 item_id 的值将作为参数 item_id 传递给 read_item() 函数。
预设值
from enum import Enum
from fastapi import FastAPI
# 创建一个 python 枚举
class ModelName(str, Enum):
alexnet = "alexnet"
resnet = "resnet"
lenet = "lenet"
app = FastAPI()
@app.get("/models/{model_name}")
async def get_model(model_name: ModelName):
if model_name is ModelName.alexnet:
return {"model_name": model_name, "message": "Deep Learning FTW!"}
if model_name.value == "lenet":
return {"model_name": model_name, "message": "LeCNN all the images"}
return {"model_name": model_name, "message": "Have some residuals"}
相关信息
请求体
- 请求体是客户端发送给 API 的数据。
- 响应体是 API 发送给客户端的数据。
使用 Pydantic 模型来声明请求体
from typing import Union
from fastapi import FastAPI
# 从 pydantic 中导入 BaseModel:
from pydantic import BaseModel
# 创建数据模型
class Item(BaseModel):
name: str
description: Union[str, None] = None #默认值为None,是一个可选属性
price: float
tax: Union[float, None] = None
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
return item
请求文件
安装依赖库
pip3 install python-multipart
Fastapi 可通过 bytes 形式和 UploadFile 形式读取和接收文件内容;
- bytes形式是将文件存储在内存中,适合小型文件;
- UploadFile形式忽略内存限制,可传输大型文件。
from fastapi import FastAPI, File, UploadFile
app = FastAPI()
# bytes 形式
@app.post("/files/")
async def create_file(file: bytes = File(description="A file read as bytes")):
return {"file_size": len(file)}
# UploadFile 形式
@app.post("/uploadfile/")
async def create_upload_file(
file: UploadFile = File(description="A file read as UploadFile"),
):
return {"filename": file.filename}