在 FastAPI 中,Depends
、Form
、Query
、Body
和 File
用于处理不同类型的请求数据。
Depends
(依赖注入)Depends
主要用于引入依赖,比如权限验证、数据库连接等,FastAPI 会自动调用被依赖的函数,并将返回值传递给视图函数。
from fastapi import FastAPI, Depends
app = FastAPI()
def get_current_user():
return {"username": "Alice", "role": "admin"}
@app.get("/profile")
def profile(user=Depends(get_current_user)):
return user
curl
请求:curl -X 'GET' 'http://127.0.0.1:8000/profile' -H 'accept: application/json'
说明:
get_current_user()
,并返回固定的 {"username": "Alice", "role": "admin"}
。Form
(解析表单数据)Form
解析 application/x-www-form-urlencoded
类型的表单数据,常见于 HTML 表单提交(如登录)。
from fastapi import FastAPI, Form
app = FastAPI()
@app.post("/login")
def login(username: str = Form(), password: str = Form()):
return {"username": username, "password": password}
curl
请求:curl -X 'POST' 'http://127.0.0.1:8000/login' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'username=admin&password=123456'
说明:
-d 'username=admin&password=123456'
以 key=value
形式传递表单数据。Query
(解析 URL 查询参数)Query
解析 GET
请求的查询参数,通常用于筛选、分页等功能。
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/search")
def search(keyword: str = Query(..., min_length=2, max_length=50), page: int = Query(1, ge=1)):
return {"keyword": keyword, "page": page}
curl
请求:curl -X 'GET' 'http://127.0.0.1:8000/search?keyword=fastapi&page=1' -H 'accept: application/json'
说明:
?keyword=fastapi&page=1
。Body
(解析 JSON 请求体数据)Body
解析 application/json
类型的请求体,通常用于 POST
、PUT
请求,例如用户注册。
from fastapi import FastAPI, Body
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
username: str
age: int
@app.post("/register")
def register(user: User = Body(...)):
return {"username": user.username, "age": user.age}
curl
请求:curl -X 'POST' 'http://127.0.0.1:8000/register' \
-H 'Content-Type: application/json' \
-d '{"username": "Alice", "age": 25}'
说明:
-d '{"username": "Alice", "age": 25}'
传递 JSON 数据。File
(解析上传的文件)File
解析 multipart/form-data
方式的文件上传请求。
from fastapi import FastAPI, File, UploadFile
app = FastAPI()
@app.post("/upload")
def upload_file(file: UploadFile = File(...)):
return {"filename": file.filename, "content_type": file.content_type}
curl
请求:curl -X 'POST' 'http://127.0.0.1:8000/upload' \
-H 'Content-Type: multipart/form-data' \
-F 'file=@/path/to/file.txt'
说明:
-F 'file=@/path/to/file.txt'
指定本地文件路径 /path/to/file.txt
进行上传。方法 | 适用场景 | 传输方式 | curl 示例 |
---|---|---|---|
Depends |
依赖注入(权限验证、数据库等) | N/A | curl -X 'GET' 'http://127.0.0.1:8000/profile' |
Form |
表单数据提交(登录、注册) | application/x-www-form-urlencoded |
curl -X 'POST' 'http://127.0.0.1:8000/login' -d 'username=admin&password=123456' |
Query |
URL 查询参数(GET 请求) | ?key=value |
curl -X 'GET' 'http://127.0.0.1:8000/search?keyword=fastapi&page=1' |
Body |
解析 JSON 数据(POST、PUT 请求) | application/json |
curl -X 'POST' 'http://127.0.0.1:8000/register' -d '{"username": "Alice", "age": 25}' |
File |
文件上传 | multipart/form-data |
curl -X 'POST' 'http://127.0.0.1:8000/upload' -F 'file=@/path/to/file.txt' |
不同的参数解析方式适用于不同的 HTTP 请求场景,可以结合 curl
命令进行测试和调试。