5.2 创建和使用依赖项
FastAPI依赖项教程:初学者如何轻松创建和使用Python依赖项
面向Python初学者的FastAPI依赖项指南,通过生活化类比和动手实践,快速掌握创建和使用依赖项的方法。
FastAPI入门教程:创建和使用依赖项
什么是依赖项?
在FastAPI中,依赖项(Dependencies)是一种强大的工具,让你可以将公共逻辑(如认证、数据库连接等)分离出来,然后在多个API端点中重用。想象一下,你点一杯咖啡时,咖啡师(你的API函数)需要咖啡豆和牛奶(依赖项)来制作咖啡。依赖项就像是这些原料,而咖啡师就是需要它们来工作的函数。这让你的代码更整洁、更易于维护。
为什么使用依赖项?
使用依赖项可以减少代码重复,提高可读性,并易于测试。它让Web开发变得更模块化,就像把一个复杂任务分解成多个小步骤。
安装和设置
首先,确保你已经安装了FastAPI和Uvicorn(一个快速的ASGI服务器)。打开终端,运行:
pip install fastapi uvicorn
然后,创建一个新的Python文件,比如 main.py,我们将在其中编写代码。
创建第一个依赖项:简单消息示例
让我们从一个超简单的例子开始,体验一下"成功时刻"。我们将创建一个依赖项,返回一个欢迎消息。
代码示例
from fastapi import Depends, FastAPI
app = FastAPI()
# 定义依赖项函数:它返回一个字符串
def get_welcome_message():
return "Welcome to FastAPI with dependencies!"
@app.get("/")
def read_root(message: str = Depends(get_welcome_message)):
# 使用Depends将依赖项注入到message参数中
return {"message": message}
运行和测试
- 保存文件为
main.py。 - 在终端运行服务器:
uvicorn main:app --reload - 打开浏览器,访问
http://127.0.0.1:8000/。 - 你会立刻看到输出:
{"message": "Welcome to FastAPI with dependencies!"}
恭喜!你已经成功创建并使用了第一个依赖项。是不是很简单?
依赖项带参数:个性化问候
依赖项就像普通函数,可以接受参数。让我们添加一个带参数的例子,让体验更个性化。
代码示例
from fastapi import Depends, FastAPI
app = FastAPI()
# 依赖项带一个参数name
def get_greeting(name: str):
return f"Hello, {name}! Glad to have you here."
@app.get("/greet/{name}")
def greet_user(greeting: str = Depends(get_greeting)):
# FastAPI自动从路径参数name传递给依赖项
return {"greeting": greeting}
运行和测试
- 确保服务器在运行(如果停止,重新运行
uvicorn main:app --reload)。 - 访问
http://127.0.0.1:8000/greet/Alice,你会看到:{"greeting": "Hello, Alice! Glad to have you here."} - 尝试其他名字,比如
http://127.0.0.1:8000/greet/Bob,看到个性化的问候。
又一个成功时刻!依赖项现在可以根据输入动态工作了。
生活化类比:依赖项就像厨师助手
想象你在开一家餐厅,厨师(API函数)负责做菜。但厨师需要助手(依赖项)来准备食材,比如切蔬菜或检查库存。助手处理重复任务,让厨师专注于烹饪。类似地,依赖项处理公共任务(如验证用户),让你的API函数更专注。
更实用的例子:简单用户认证
依赖项常用于用户认证,比如检查令牌。这里是一个简化版示例,建立信心。
代码示例
from fastapi import Depends, FastAPI, HTTPException, Header
app = FastAPI()
# 模拟一个简单的用户数据库
fake_users = {
"token123": {"username": "alice", "role": "user"},
"token456": {"username": "bob", "role": "admin"}
}
def get_current_user(authorization: str = Header(None)):
"""
依赖项函数:检查Authorization头,返回用户信息或抛出错误
类比:助手检查顾客的会员卡是否有效
"""
if authorization is None:
raise HTTPException(status_code=401, detail="No authorization header provided")
# 假设头格式为 "Bearer token123"
if authorization.startswith("Bearer "):
token = authorization.split(" ")[1]
if token in fake_users:
return fake_users[token]
raise HTTPException(status_code=401, detail="Invalid or expired token")
@app.get("/profile")
def user_profile(user: dict = Depends(get_current_user)):
# 使用依赖项注入的用户信息
return {"username": user["username"], "role": user["role"]}
运行和测试
- 使用浏览器或工具(如curl或Postman)测试。例如,发送GET请求到
http://127.0.0.1:8000/profile,头部添加Authorization: Bearer token123。 - 你会得到响应:
{"username": "alice", "role": "user"}。 - 如果去掉头部或用无效令牌,你会看到错误消息,如
{"detail": "No authorization header provided"}。
看,依赖项帮你处理了认证逻辑,让API更安全!
动手实践:自己创建依赖项
现在,轮到你了!创建一个依赖项来计算两个数的和,并在API中使用它。
任务
- 依赖项函数
add_numbers(a: int, b: int),返回两个数的和。 - 在路径
/add/{a}/{b}中使用这个依赖项。
提示代码
from fastapi import Depends, FastAPI
app = FastAPI()
def add_numbers(a: int, b: int):
return a + b
@app.get("/add/{a}/{b}")
def get_sum(result: int = Depends(add_numbers)):
return {"sum": result}
运行服务器,访问 http://127.0.0.1:8000/add/5/3,你应该看到 {"sum": 8}。试试其他数字,感受依赖项的灵活性!
总结
今天,你学会了FastAPI中依赖项的基础:从创建一个简单的消息依赖项,到带参数的问候,再到实用的认证示例。依赖项让代码更模块化,易于重用和测试。
关键要点:
- 依赖项是函数,用
Depends()注入到API端点中。 - 类比生活场景(如厨师助手)帮助理解概念。
- 通过动手实践,快速建立信心。
继续探索FastAPI,尝试将依赖项用于数据库连接、配置设置等场景,让你的Web应用更强大!如果有问题,参考FastAPI官方文档或社区资源。