1.基础用法
1 | from fastapi import FastAPI, Request |
- 通过声明
Request类型参数直接获取请求对象 - 请求处理流程:
graph TD A[请求到达] --> B{路径参数解析} B --> C[注入Request对象] C --> D[访问client.host等属性] D --> E[返回响应数据]
2.请求对象核心特性
2.1 数据访问层级
- 基础属性:
1
2
3request.method # 请求方法(GET/POST等)
request.url.path # 请求路径
request.client.port # 客户端端口号 - 底层数据:
1
2request.scope # 原始ASGI scope字典
request.scope["headers"] # 原始头信息字节列表 - 协议信息:
1
2request.base_url # 基础URL(含协议和主机)
request.http_version # HTTP协议版本
2.2 数据获取方法
1 | # 获取查询参数 |
3.进阶配置
3.1 中间件集成
1 |
|
- 在中间件中访问请求对象实现全局处理
3.2 数据流处理
1 |
|
- 使用流式处理应对大文件上传场景
4.生产环境建议
安全访问:
- 使用
request.client代替直接解析X-Forwarded-For头 - 敏感信息访问需配合HTTPS加密
- 使用
性能优化:
- 避免在业务逻辑中频繁访问
request.scope - 对常用数据做本地缓存(如
request.method)
- 避免在业务逻辑中频繁访问
错误处理:
1
2
3
4from starlette.exceptions import HTTPException
async def custom_handler(request: Request, exc: HTTPException):
return JSONResponse({"detail": exc.detail}, status_code=exc.status_code)
测试命令示例:
1 curl http://localhost:8000/items/123