VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • FastAPI Cookie 和 Header 参数完全指南:从基础到高级实战

第一章:Cookie 参数基础
1.1 什么是 Cookie 参数?
Cookie 是 Web 应用中用于存储用户会话信息的机制。在 FastAPI 中,Cookie 参数可以通过 Cookie 类进行处理。

PYTHON

from fastapi import FastAPI, Cookie

app = FastAPI()


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

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

PYTHON

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

示例请求:

BASH
curl -b "session_id=abc123" http://localhost:8000/items/
1.3 Cookie 参数校验
结合 Pydantic 的 Field,可以对 Cookie 参数进行数据校验。

PYTHON

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 类进行处理。

PYTHON

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 参数。

PYTHON

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

示例请求:

BASH
curl -H "X-Token: abc123" http://localhost:8000/user/
2.3 Header 参数校验
结合 Pydantic 的 Field,可以对 Header 参数进行数据校验。

PYTHON

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 参数的类型定义和校验规则。

第三章:高级用法与最佳实践
3.1 自定义 Cookie 和 Header 名称
通过 alias 参数,可以自定义 Cookie 和 Header 的名称。

PYTHON

@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 安全性最佳实践
通过 Secure 和 HttpOnly 标志,可以增强 Cookie 的安全性。

PYTHON

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 性能优化
通过 Header 的 convert_underscores 参数,可以优化 Header 参数的兼容性。

PYTHON

@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 参数?
答案:

PYTHON

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 参数?
答案:

PYTHON

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 类型转换失败/校验不通过 检查参数定义的校验规则
400 Header 或 Cookie 格式不正确 检查参数的格式和校验规则
500 未捕获的参数处理异常 添加 try/except 包裹敏感操作
401 未授权访问 检查认证和授权逻辑
常见问题解答    
Q:如何设置安全的 Cookie?    
A:通过 Secure 和 HttpOnly 标志设置:    

PYTHON

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 参数设置:

PYTHON

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

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

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

来源:https://blog.cmdragon.cn/posts/143aef8a44f0/


相关教程