mcpField
F
fastapi-templates

fastapi-templates

github.com/wshobson开发41.9k26.1k 次安装2 周前更新
代码仓库

关于 fastapi-templates

fastapi-templates 提供 FastAPI 项目结构与实现模式,面向构建异步 API 的开发者,涵盖依赖注入、中间件和测试。

主要功能

  1. 01FastAPI 项目结构
  2. 02异步路由与数据库模式
  3. 03依赖注入实践
  4. 04中间件模式
  5. 05异步测试示例

适用场景

  1. 01从头搭建 FastAPI 项目
  2. 02实现异步 REST API
  3. 03规划 PostgreSQL 或 MongoDB 应用
  4. 04为 API 设置测试结构

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/wshobson/agents --skill fastapi-templates

安装后在 Claude Code 中输入/fastapi-templates确认已加载。

附带文件references/details.md

详细介绍

FastAPI 项目模板

可用于生产环境的 FastAPI 项目结构,涵盖异步模式、依赖注入、中间件和最佳实践,助你构建高性能 API。

何时使用此技能

  • 从头开始创建新的 FastAPI 项目
  • 使用 Python 实现异步 REST API
  • 构建高性能 Web 服务和微服务
  • 使用 PostgreSQL、MongoDB 创建异步应用
  • 搭建结构完善且包含测试的 API 项目

核心概念

1. 项目结构

推荐布局:

app/
├── api/                    # API routes
│   ├── v1/
│   │   ├── endpoints/
│   │   │   ├── users.py
│   │   │   ├── auth.py
│   │   │   └── items.py
│   │   └── router.py
│   └── dependencies.py     # Shared dependencies
├── core/                   # Core configuration
│   ├── config.py
│   ├── security.py
│   └── database.py
├── models/                 # Database models
│   ├── user.py
│   └── item.py
├── schemas/                # Pydantic schemas
│   ├── user.py
│   └── item.py
├── services/               # Business logic
│   ├── user_service.py
│   └── auth_service.py
├── repositories/           # Data access
│   ├── user_repository.py
│   └── item_repository.py
└── main.py                 # Application entry
2. 依赖注入

FastAPI 使用 Depends 提供内置的依赖注入系统:

  • 数据库会话管理
  • 身份验证/授权
  • 共享业务逻辑
  • 配置注入
3. 异步模式

正确使用 async/await:

  • 异步路由处理器
  • 异步数据库操作
  • 异步后台任务
  • 异步中间件
4. 依赖项

示例导入的包:

# requirements.txt
fastapi
uvicorn[standard]
pydantic-settings
sqlalchemy[asyncio]>=2.0  # DeclarativeBase; [asyncio] installs greenlet for the async engine
asyncpg                   # PostgreSQL driver: postgresql+asyncpg://...
PyJWT
pwdlib[argon2]
python-multipart          # only for a login route that uses OAuth2PasswordRequestForm

# requirements-dev.txt
pytest
pytest-asyncio
httpx
aiosqlite                 # test database: sqlite+aiosqlite:///:memory:

详细示例与模式

详细章节(从 ## Implementation Patterns 开始)位于 references/details.md。如果上面的导航摘要无法满足需求,请阅读该文件。

测试

# tests/conftest.py
import pytest_asyncio
from httpx import ASGITransport, AsyncClient
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker

from app.main import app
from app.core.database import get_db, Base

TEST_DATABASE_URL = "sqlite+aiosqlite:///:memory:"

# Async fixtures need pytest_asyncio.fixture in pytest-asyncio's default strict mode
@pytest_asyncio.fixture
async def db_session():
    engine = create_async_engine(TEST_DATABASE_URL, echo=True)
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)

    AsyncSessionLocal = sessionmaker(
        engine, class_=AsyncSession, expire_on_commit=False
    )

    async with AsyncSessionLocal() as session:
        yield session
    await engine.dispose()

@pytest_asyncio.fixture
async def client(db_session):
    async def override_get_db():
        yield db_session

    app.dependency_overrides[get_db] = override_get_db

    # httpx 0.28 removed AsyncClient(app=...); use an ASGI transport
    transport = ASGITransport(app=app)
    async with AsyncClient(transport=transport, base_url="http://test") as client:
        yield client
    app.dependency_overrides.clear()

# tests/test_users.py
import pytest

@pytest.mark.asyncio
async def test_create_user(client):
    response = await client.post(
        "/api/v1/users/",
        json={
            "email": "[email protected]",
            "password": "testpass123",
            "name": "Test User"
        }
    )
    assert response.status_code == 201
    data = response.json()
    assert data["email"] == "[email protected]"
    assert "id" in data

评论

支持 Markdown