360 Secure SkillHub
360 安全技能中心

fastapi-best-practices

该 Skill 是一份 FastAPI 中文最佳实践指南,包含项目结构示例、路由模板、错误处理示例和开发建议,内容以 Markdown 文档和 Python 代码片段呈现,供后端开发参考。

guyulong
热度 0.00
最近更新 2026-10-18 23:40:10
分类:开发依赖:纯提示词应用场景:代码生成 / API 集成 / 模板

安装技能

复制下面的话术发给你的 Agent,它会通过 secure-skills 检索并安装该技能。

执行命令安装此 skill: npx secure-skills-cli add guyulong/cn-agent-skills/fastapi-best-practices
Metadata
name
fastapi-best-practices
description
FastAPI中文最佳实践指南
category
后端开发
tags
["fastapi","python","后端","API"]
tools
["claude-code","cursor","copilot"]

FastAPI 中文最佳实践

项目结构

├── app/
│   ├── __init__.py
│   ├── main.py           # 入口文件
│   ├── config.py          # 配置
│   ├── database.py        # 数据库连接
│   ├── models/            # 数据模型
│   │   ├── user.py
│   │   └── order.py
│   ├── schemas/           # Pydantic模型
│   │   ├── user.py
│   │   └── order.py
│   ├── api/               # API路由
│   │   ├── v1/
│   │   │   ├── user.py
│   │   │   └── order.py
│   │   └── deps.py        # 依赖注入
│   ├── services/          # 业务逻辑
│   │   └── user.py
│   └── utils/             # 工具函数
│       └── security.py
├── tests/
├── alembic/               # 数据库迁移
├── requirements.txt
└── .env

路由模板

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.api.deps import get_db, get_current_user
from app.schemas.user import UserCreate, UserResponse
from app.services.user import UserService

router = APIRouter(prefix="/users", tags=["用户"])

@router.post("/", response_model=UserResponse, summary="创建用户")
async def create_user(
    user_in: UserCreate,
    db: Session = Depends(get_db)
):
    """
    创建新用户
    
    - **username**: 用户名,3-20个字符
    - **password**: 密码,至少8位
    - **phone**: 手机号,11位数字
    """
    service = UserService(db)
    user = await service.create(user_in)
    return user

@router.get("/{user_id}", response_model=UserResponse, summary="获取用户信息")
async def get_user(
    user_id: int,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """根据用户ID获取用户信息"""
    service = UserService(db)
    user = await service.get_by_id(user_id)
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    return user

错误处理

from fastapi import HTTPException
from fastapi.responses import JSONResponse

class AppException(Exception):
    def __init__(self, code: int, message: str):
        self.code = code
        self.message = message

@app.exception_handler(AppException)
async def app_exception_handler(request, exc):
    return JSONResponse(
        status_code=200,
        content={"code": exc.code, "message": exc.message, "data": None}
    )

# 使用
raise AppException(code=1001, message="用户名已存在")

最佳实践

  • 使用 Pydantic 做数据验证
  • 依赖注入管理数据库连接
  • 中文注释和文档
  • 统一错误响应格式
  • 使用 async/await
  • 配置 CORS
  • 使用环境变量管理配置