FastAPI Cookie 和 Header 参数完全指南:从基础到高级实战 🚀

avatar
cmdragon 渡劫
image image

扫描二维码关注或者微信搜一搜:编程智域 前端至全栈交流与成长

探索数千个预构建的 AI 应用,开启你的下一个伟大创意

第一章:Cookie 参数基础

Cookie 是 Web 应用中用于存储用户会话信息的机制。在 FastAPI 中,Cookie 参数可以通过 Cookie 类进行处理。

1
2
3
4
5
6
7
8
from fastapi import FastAPI, Cookie

app = FastAPI()


@app.get("/items/")
async def read_items(session_id: str = Cookie(None)):
return {"session_id": session_id}

通过 Cookie 类,可以轻松读取客户端传递的 Cookie 参数。

1
2
3
@app.get("/user/")
async def read_user(user_id: str = Cookie(None)):
return {"user_id": user_id}

示例请求

1
curl -b "session_id=abc123" http://localhost:8000/items/

结合 Pydantic 的 Field,可以对 Cookie 参数进行数据校验。

1
2
3
4
5
6
from pydantic import Field


@app.get("/validate-cookie/")
async def validate_cookie(session_id: str = Cookie(..., min_length=3)):
return {"session_id": session_id}

示例请求

  • 合法:curl -b "session_id=abc123" http://localhost:8000/validate-cookie/{"session_id": "abc123"}
  • 非法:curl -b "session_id=a" http://localhost:8000/validate-cookie/ → 422 错误

1.4 常见错误与解决方案

错误:422 Validation Error
原因:Cookie 参数类型转换失败或校验不通过
解决方案:检查 Cookie 参数的类型定义和校验规则。


第二章:Header 参数基础

2.1 什么是 Header 参数?

Header 是 HTTP 请求中用于传递元数据的机制。在 FastAPI 中,Header 参数可以通过 Header 类进行处理。

1
2
3
4
5
6
7
8
from fastapi import FastAPI, Header

app = FastAPI()


@app.get("/items/")
async def read_items(user_agent: str = Header(None)):
return {"user_agent": user_agent}

2.2 Header 参数的使用

通过 Header 类,可以轻松读取客户端传递的 Header 参数。

1
2
3
@app.get("/user/")
async def read_user(x_token: str = Header(None)):
return {"x_token": x_token}

示例请求

1
curl -H "X-Token: abc123" http://localhost:8000/user/

2.3 Header 参数校验

结合 Pydantic 的 Field,可以对 Header 参数进行数据校验。

1
2
3
4
5
6
from pydantic import Field


@app.get("/validate-header/")
async def validate_header(x_token: str = Header(..., min_length=3)):
return {"x_token": x_token}

示例请求

  • 合法:curl -H "X-Token: abc123" http://localhost:8000/validate-header/{"x_token": "abc123"}
  • 非法:curl -H "X-Token: a" http://localhost:8000/validate-header/ → 422 错误

2.4 常见错误与解决方案

错误:422 Validation Error
原因:Header 参数类型转换失败或校验不通过
解决方案:检查 Header 参数的类型定义和校验规则。


第三章:高级用法与最佳实践

通过 alias 参数,可以自定义 Cookie 和 Header 的名称。

1
2
3
4
5
6
7
8
@app.get("/custom-cookie/")
async def custom_cookie(session: str = Cookie(None, alias="session_id")):
return {"session": session}


@app.get("/custom-header/")
async def custom_header(token: str = Header(None, alias="X-Token")):
return {"token": token}

3.2 安全性最佳实践

通过 SecureHttpOnly 标志,可以增强 Cookie 的安全性。

1
2
3
4
5
6
7
8
from fastapi.responses import JSONResponse


@app.get("/secure-cookie/")
async def secure_cookie():
response = JSONResponse(content={"message": "Secure cookie set"})
response.set_cookie(key="session_id", value="abc123", secure=True, httponly=True)
return response

3.3 性能优化

通过 Headerconvert_underscores 参数,可以优化 Header 参数的兼容性。

1
2
3
@app.get("/optimized-header/")
async def optimized_header(user_agent: str = Header(None, convert_underscores=False)):
return {"user_agent": user_agent}

3.4 常见错误与解决方案

错误:400 Bad Request
原因:Header 或 Cookie 参数格式不正确
解决方案:检查参数的格式和校验规则。


课后测验

测验 1:Cookie 参数校验

问题:如何定义一个包含校验规则的 Cookie 参数?
答案

1
2
3
4
5
6
7
from fastapi import Cookie
from pydantic import Field


@app.get("/validate-cookie/")
async def validate_cookie(session_id: str = Cookie(..., min_length=3)):
return {"session_id": session_id}

测验 2:Header 参数校验

问题:如何定义一个包含校验规则的 Header 参数?
答案

1
2
3
4
5
6
7
from fastapi import Header
from pydantic import Field


@app.get("/validate-header/")
async def validate_header(x_token: str = Header(..., min_length=3)):
return {"x_token": x_token}

错误代码应急手册

错误代码典型触发场景解决方案
422类型转换失败/校验不通过检查参数定义的校验规则
400Header 或 Cookie 格式不正确检查参数的格式和校验规则
500未捕获的参数处理异常添加 try/except 包裹敏感操作
401未授权访问检查认证和授权逻辑

常见问题解答

Q:如何设置安全的 Cookie?
A:通过 SecureHttpOnly 标志设置:

1
2
3
4
5
6
7
8
from fastapi.responses import JSONResponse


@app.get("/secure-cookie/")
async def secure_cookie():
response = JSONResponse(content={"message": "Secure cookie set"})
response.set_cookie(key="session_id", value="abc123", secure=True, httponly=True)
return response

Q:如何处理自定义 Header 名称?
A:通过 alias 参数设置:

1
2
3
@app.get("/custom-header/")
async def custom_header(token: str = Header(None, alias="X-Token")):
return {"token": token}

通过本教程的详细讲解和实战项目,您已掌握 FastAPI 中 Cookie 和 Header 参数的核心知识。现在可以通过以下命令测试您的学习成果:

1
curl -b "session_id=abc123" http://localhost:8000/items/

余下文章内容请点击跳转至 个人博客页面 或者 扫码关注或者微信搜一搜:编程智域 前端至全栈交流与成长,阅读完整的文章:

往期文章归档: