FastAPI的使用
课程地址
FastAPI交互调试页面
运行命令
文件名为 1.py :
python -m uvicorn 1:app --reloadFastAPI基础
路由 路径参数 查询参数
from fastapi import FastAPI,Path, Query
app = FastAPI()
@app.get("/")
async def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
@app.get("/news/{news_id}")
async def read_news(news_id: int = Path(gt=0, lt=10, description="The ID of the news item to retrieve")):
return {"news_id": news_id}
@app.get("/news/{news_name}")
async def read_news_by_name(news_name: str=Path(..., min_length=3, max_length=50, description="The name of the news item to retrieve")):
return {"news_name": news_name}
@app.get("/books/find")
async def find_books(category:str=Query(None, description="The category of books to find"), price:int=Query(None, description="The maximum price of books to find")):
return {"category": category, "price": price}Pydantic
Pydantic 是 Python 后端开发中非常常用的一个库,FastAPI 使用 Pydantic 定义数据结构、校验请求参数,并把数据转换成 Python 对象。
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int请求体参数
用于创建、更新资源,即向服务器提供数据。
from fastapi import FastAPI
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int
app=FastAPI()
@app.post("/users/")
async def create_user(user: User):
return {"user message":user}响应类型
服务器收到请求后需做出相应,默认的响应类型为JSON。
JSON response

HTML response
装饰器指定响应类型:
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
app=FastAPI()
@app.get("/html", response_class=HTMLResponse)
async def get_html():
return "<h1>Hello, World!</h1>"不指定直接返回响应对象:
from fastapi.responses import HTMLResponse,FileResponse
@app.get("/image")
async def get_image():
return FileResponse("./files/OIP-C.jpg")自定义响应数据格式
class User(BaseModel):
name: str
age: int
@app.post("/users/", response_model=User)
async def create_user(user: User):
return user异常处理
对于客户端(或者说客户)引发的错误(4xx,如资源未找到、认证失败),应使用 fastapi.HTTPException 来中断正常处理流程,并返回标准错误响应。
from fastapi import FastAPI,HTTPException
app=FastAPI()
list1=[1,2,3,4,5]
@app.get("/items/{id}")
async def find_id(id: int):
if id not in list1:
raise HTTPException(detail="Item not found",status_code=404)
return{"item_id":id}FastAPI进阶
中间件
为每个接口添加统一的处理逻辑,如 日志记录、身份认证、跨域处理、性能监控。

from fastapi import FastAPI,HTTPException
app=FastAPI()
@app.middleware("http")
async def middleware1(request, call_next):
print("middleware1 start")
response=await call_next(request)
print("middleware1 end")
return response
list1=[1,2,3,4,5]
@app.get("/items/{id}")
async def find_id(id: int):
if id not in list1:
raise HTTPException(detail="Item not found",status_code=404)
return{"item_id":id}中间件先执行完,然后才执行路由处理函数,如果有多个中间件,会按中间件定义顺序把中间件注册到栈,执行时按栈的弹出顺序一次执行。也就是说,先定义的中间件会在栈底,最后执行。
依赖注入
中间件作用于所有路由,依赖注入作用于指定路由。
from fastapi import FastAPI, Depends, HTTPException, Header
app = FastAPI()
# 1. 定义依赖函数:验证用户 Token
def verify_token(token: str = Header()):
if token != "123456":
raise HTTPException(
status_code=401,
detail="Token 无效"
)
return "张三"
# 2. 定义路由函数
@app.get("/items/{item_id}")
async def get_item(
item_id: int,
username: str = Depends(verify_token)
):
return {
"item_id": item_id,
"username": username
}ORM
ORM(Object-Relational Mapping,对象关系映射)是一种编程技术,用于在面向对象编程语言和关系型数据库之间建立映射。它允许开发者通过操作对象的方式与数据库进行交互,而无需直接编写复杂的 SQL 语句。所以需要先安装mysql server,不一定安装在本地,远程有可连接的数据库实例也可以。
版本选取
使用sqlalchemy ORM,企业使用最多,社区最活跃。
安装命令
s省略ORM各种操作的介绍
文章作者:shuimqy
文章链接:https://www.shuimqy.art//archives/fastapide-shi-yong
版权声明:本博客所有文章除特别声明外,均采用CC BY-NC-SA 4.0 许可协议,转载请注明出处!
评论已关闭!