python-fastapi
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesepython-fastapi
Python-FastAPI
This skill defines how to build APIs using FastAPI following best
practices in architecture, security, maintainability, and performance.
This is the minimum acceptable standard.
本实践指导如何遵循架构、安全、可维护性及性能方面的最佳实践,使用FastAPI构建API。以下是最低可接受标准。
When to use
适用场景
Use when you need to build APIs using FastAPI following best practices in architecture, security, maintainability, and performance.
当你需要遵循架构、安全、可维护性及性能最佳实践,使用FastAPI构建API时,可参考本规范。
Instructions
实施指南
1. Core Principles
1. 核心原则
- Secure by default.
- Strict typing and strong validation.
- Clear separation of concerns.
- No business logic inside routers.
- Zero hardcoded secrets.
- Fail closed, not fail open.
If it "works but is insecure", it does not work.
- 默认安全
- 严格类型检查与强校验
- 关注点清晰分离
- 路由中不包含业务逻辑
- 禁止硬编码密钥
- 故障时默认关闭,而非开放
任何“能运行但不安全”的实现都不能算合格。
2. Project Structure
2. 项目结构
Recommended minimum structure:
app/
├── main.py
├── api/
│ ├── deps.py
│ └── v1/
│ ├── routes_x.py
├── core/
│ ├── config.py
│ ├── security.py
│ └── logging.py
├── services/
├── repositories/
├── models/
└── schemas/Rules:
- → endpoints only.
api/ - → business logic.
services/ - → data access.
repositories/ - → Pydantic request/response models.
schemas/ - → configuration, security, cross-cutting concerns.
core/
Everything inside is not minimalism. It is chaos.
main.py推荐的最小项目结构:
app/
├── main.py
├── api/
│ ├── deps.py
│ └── v1/
│ ├── routes_x.py
├── core/
│ ├── config.py
│ ├── security.py
│ └── logging.py
├── services/
├── repositories/
├── models/
└── schemas/规则:
- → 仅存放API端点
api/ - → 业务逻辑
services/ - → 数据访问层
repositories/ - → Pydantic请求/响应模型
schemas/ - → 配置、安全及横切关注点
core/
将所有代码都放在中不是极简,而是混乱。
main.py3. Secure Configuration
3. 安全配置
3.1 Environment Variables
3.1 环境变量
Use .
pydantic-settingspython
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
app_name: str
environment: str
secret_key: str
database_url: str
access_token_expire_minutes: int = 15
class Config:
env_file = ".env"Rules:
- No default values for secrets.
- No secrets in the repository.
- files are forbidden in production.
.env
使用。
pydantic-settingspython
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
app_name: str
environment: str
secret_key: str
database_url: str
access_token_expire_minutes: int = 15
class Config:
env_file = ".env"规则:
- 密钥不设置默认值
- 密钥不存入代码仓库
- 生产环境禁止使用文件
.env
4. Authentication Security
4. 认证安全
4.1 Never Custom Authentication
4.1 禁止自定义认证
Use: - OAuth2 + JWT - Or a trusted identity provider (Auth0, Cognito,
Keycloak, etc.)
使用:- OAuth2 + JWT - 或可信身份提供商(Auth0, Cognito, Keycloak等)
4.2 Secure JWT
4.2 安全的JWT配置
- Signed with HS256 or RS256.
- Short expiration time.
- Validate:
- exp
- iss
- aud
Never trust the payload without verifying the signature.
- 使用HS256或RS256签名
- 短过期时间
- 验证以下字段:
- exp(过期时间)
- iss(签发者)
- aud(受众)
未验证签名前,绝不要信任JWT负载内容。
5. Endpoint Security
5. 端点安全
5.1 Dependency Injection for Security
5.1 依赖注入实现安全校验
python
from fastapi import Depends, HTTPException, status
def get_current_user(token: str = Depends(oauth2_scheme)):
...Rules:
- Every sensitive route must require authentication.
- Separate authentication from authorization.
- Implement explicit RBAC or ABAC.
python
from fastapi import Depends, HTTPException, status
def get_current_user(token: str = Depends(oauth2_scheme)):
...规则:
- 所有敏感路由必须要求认证
- 认证与授权分离
- 实现明确的RBAC(基于角色的访问控制)或ABAC(基于属性的访问控制)
5.2 Strict Validation with Pydantic
5.2 使用Pydantic进行严格校验
Always use models:
python
class UserCreate(BaseModel):
email: EmailStr
password: constr(min_length=12)Rules:
- Never accept raw dicts.
- Avoid unless absolutely necessary.
Any - Limit string sizes.
- Validate nested structures.
始终使用模型:
python
class UserCreate(BaseModel):
email: EmailStr
password: constr(min_length=12)规则:
- 绝不接受原始字典
- 除非绝对必要,否则避免使用类型
Any - 限制字符串长度
- 校验嵌套结构
6. OWASP Top 10 Protection
6. OWASP Top 10防护
6.1 Injection
6.1 注入攻击防护
- Never build SQL queries manually.
- Use ORM or parameterized queries.
- Enforce strict typing.
- 绝不手动拼接SQL查询
- 使用ORM或参数化查询
- 强制严格类型检查
6.2 Excessive Data Exposure
6.2 过度数据暴露防护
Never return:
- Password hashes
- Tokens
- Internal fields
- Stack traces
Use explicit response models:
python
@router.get("/", response_model=UserResponse)绝不要返回以下内容:
- 密码哈希值
- 令牌
- 内部字段
- 堆栈跟踪
使用明确的响应模型:
python
@router.get("/", response_model=UserResponse)6.3 Error Handling
6.3 错误处理
Do not expose internal errors.
python
@app.exception_handler(Exception)
async def global_exception_handler(request, exc):
return JSONResponse(
status_code=500,
content={"detail": "Internal server error"},
)Log internally. Do not leak details externally.
不要暴露内部错误信息。
python
@app.exception_handler(Exception)
async def global_exception_handler(request, exc):
return JSONResponse(
status_code=500,
content={"detail": "Internal server error"},
)内部记录日志,不要向外泄露细节。
7. Rate Limiting and Abuse Protection
7. 速率限制与滥用防护
Implement rate limiting:
- SlowAPI or equivalent.
- Or external gateway (NGINX, API Gateway).
Rules: - Never expose login without rate limiting. - Never expose public
endpoints without abuse control.
实现速率限制:
- 使用SlowAPI或同类工具
- 或通过外部网关(NGINX、API网关)实现
规则:- 登录端点必须启用速率限制 - 公开端点必须启用滥用控制
8. Secure CORS
8. 安全的CORS配置
Never:
python
allow_origins=["*"]
allow_credentials=TrueExplicitly configure allowed origins per environment.
绝不要这样配置:
python
allow_origins=["*"]
allow_credentials=True根据环境明确配置允许的源。
9. Secure Logging
9. 安全日志
- Do not log passwords.
- Do not log tokens.
- Do not log sensitive data.
- Use structured logging (JSON).
- Include request_id.
If you feel the need to log the full request body, rethink your
architecture.
- 不要记录密码
- 不要记录令牌
- 不要记录敏感数据
- 使用结构化日志(JSON格式)
- 包含request_id
如果你觉得需要记录完整请求体,请重新审视你的架构。
10. File Upload Security
10. 文件上传安全
If uploads are allowed:
- Enforce size limits.
- Validate MIME type.
- Do not trust file extensions.
- Never execute uploaded content.
- Store outside public root.
如果允许文件上传:
- 强制限制文件大小
- 校验MIME类型
- 不要信任文件扩展名
- 绝不执行上传的内容
- 存储在公共根目录之外
11. Production Hardening
11. 生产环境加固
11.1 Server
11.1 服务器配置
Never use:
uvicorn main:app --reloadUse:
- Gunicorn + Uvicorn workers
- Proper worker configuration
- Reverse proxy in front
绝不要使用:
uvicorn main:app --reload应使用:
- Gunicorn + Uvicorn工作进程
- 合理的工作进程配置
- 前置反向代理
11.2 Security Headers
11.2 安全头
Add:
- X-Content-Type-Options
- X-Frame-Options
- Content-Security-Policy
- Strict-Transport-Security
Preferably via middleware or reverse proxy.
添加以下安全头:
- X-Content-Type-Options
- X-Frame-Options
- Content-Security-Policy
- Strict-Transport-Security
优先通过中间件或反向代理配置。
12. Mandatory Testing
12. 强制测试
At minimum:
- Authentication tests.
- Authorization tests.
- Validation tests.
- Error handling tests.
Testing only the happy path is self-deception.
至少包含以下测试:
- 认证测试
- 授权测试
- 校验测试
- 错误处理测试
仅测试正常流程是自欺欺人。
13. Code Quality Standards
13. 代码质量标准
- Full typing.
- enabled.
mypy - or
ruff.flake8 - mandatory.
black - No logic in decorators.
- No side effects at import time.
- 完整的类型注解
- 启用
mypy - 使用或
ruffflake8 - 强制使用格式化
black - 装饰器中不包含逻辑
- 导入时不产生副作用
14. What NOT To Do
14. 禁止操作
- Do not expose in production without authentication.
/docs - Do not use DEBUG=True.
- Do not return raw exceptions.
- Do not trust frontend input.
- Do not mix sync and async blindly.
- Never use .
eval
- 生产环境中,不要在未认证的情况下暴露
/docs - 不要启用DEBUG=True
- 不要返回原始异常
- 不要信任前端输入
- 不要随意混合同步与异步代码
- 绝不要使用
eval
15. Pre-Deployment Checklist
15. 部署前检查清单
- Environment variables secured
- Secrets outside repository
- Rate limiting enabled
- Restricted CORS
- Logs free of sensitive data
- JWT validates signature and expiration
- Auth tests passing
- Dependencies updated
- /docs protected or disabled
If this checklist is not satisfied, it is not a deployment. It is a
gamble.
- 环境变量已安全配置
- 密钥未存入代码仓库
- 已启用速率限制
- CORS已严格配置
- 日志中不包含敏感数据
- JWT已验证签名和过期时间
- 认证测试全部通过
- 依赖已更新
- 已被保护或禁用
/docs
如果未满足此清单的要求,那不是部署,而是赌博。