python-development-python-scaffold
作为一名专注于生产就绪级Python应用架构设计的专家,我将为您提供结合现代化工具链(uv、FastAPI、Django)和类型提示的完整项目脚手架方案。以下是三个典型项目结构示例: --- ### **方案一:FastAPI微服务架构(uv + Pydantic + SQLAlchemy)** ``` modern-api/ ├── pyproject.toml # uv依赖管理与构建配置 ├── .python-version # Python版本锁定 ├── .env.example # 环境变量模板 ├── .gitignore ├── .pre-commit-config.yaml # Git提交前检查 │ ├── src/ │ └── api_service/ │ ├── __init__.py │ ├── main.py # FastAPI应用入口 │ ├── config/ # 配置管理 │ │ ├── __init__.py │ │ ├── settings.py # Pydantic配置模型 │ │ └── constants.py │ │ │ ├── core/ # 核心组件 │ │ ├── __init__.py │ │ ├── dependencies.py # DI依赖注入 │ │ ├── security.py # 认证授权 │ │ └── exceptions.py # 自定义异常 │ │ │ ├── domain/ # 领域模型 │ │ ├── __init__.py │ │ ├── entities.py # 纯数据类(Pydantic) │ │ └── value_objects.py │ │ │ ├── application/ # 应用服务层 │ │ ├── __init__.py │ │ ├── use_cases/ # 业务用例 │ │ │ ├── __init__.py │ │ │ └── user_management.py │ │ └── interfaces/ # 抽象接口 │ │ └── repositories.py │ │ │ ├── infrastructure/ # 基础设施层 │ │ ├── __init__.py │ │ ├── database/ │ │ │ ├── __init__.py │ │ │ ├── session.py # SQLAlchemy会话管理 │ │ │ └── models.py # ORM模型 │ │ └── repositories/ # 仓储实现 │ │ └── user_repository.py │ │ │ ├── api/ # 接口层 │ │ ├── __init__.py │ │ ├── v1/ # API版本隔离 │ │ │ ├── __init__.py │ │ │ ├── endpoints/ │ │ │ │ ├── __init__.py │ │ │ │ ├── users.py │ │ │ │ └── health.py │ │ │ └── routers.py # 路由聚合 │ │ └── middleware/ # 中间件 │ │ ├── logging.py │ │ └── rate_limit.py │ │ │ └── utils/ # 工具函数 │ ├── logging.py # 结构化日志 │ └── validators.py │ ├── tests/ # 分层测试 │ ├── unit/ │ │ ├── domain/ │ │ └── application/ │ ├── integration/ │ │ └── api/ │ ├── fixtures/ │ └── conftest.py # Pytest配置 │ ├── scripts/ # 部署运维脚本 │ ├── migration.py # 数据库迁移 │ ├── seed_data.py │ └── health_check.py │ ├── docker/ │ ├── Dockerfile │ ├── docker-compose.yml # 开发环境依赖 │ └── nginx/ │ └── default.conf │ └── docs/ # OpenAPI文档 ├── api_spec.yaml └── architecture.md ``` **关键特性:** - 采用uv作为极速包管理器和运行器 - 严格的分层架构(清洁架构) - 100%类型提示覆盖(mypy配置预设) - 异步优先设计(async/await) - 基于Pydantic v2的请求/响应验证 - SQLAlchemy 2.0异步ORM支持 --- ### **方案二:Django全栈应用(uv + Django Ninja + Celery)** ``` django-platform/ ├── pyproject.toml # uv依赖(替代requirements.txt) ├── .python-version ├── .envs/ │ ├── .local # 本地环境变量 │ ├── .production # 生产环境变量 │ └── .ci # CI环境变量 │ ├── config/ # Django项目配置 │ ├── __init__.py │ ├── settings/ # 环境分离配置 │ │ ├── __init__.py │ │ ├── base.py # 基础配置 │ │ ├── local.py │ │ └── production.py │ ├── asgi.py │ ├── urls.py │ └── wsgi.py │ ├── apps/ # 可插拔Django应用 │ ├── __init__.py │ ├── users/ # 用户管理应用 │ │ ├── __init__.py │ │ ├── models.py # 类型提示Model │ │ ├── admin.py # 强化类型提示 │ │ ├── api/ │ │ │ ├── schemas.py # Django Ninja Schema │ │ │ └── routers.py │ │ ├── services.py # 业务逻辑封装 │ │ ├── selectors.py # 查询管理器 │ │ └── migrations/ │ │ │ ├── products/ # 商品模块 │ └── common/ # 公共组件 │ ├── models.py # 抽象基类模型 │ └── mixins.py │ ├── libs/ # 内部共享库 │ ├── authentication/ │ ├── payment/ │ └── notifications.py │ ├── static/ # 静态资源 ├── templates/ # Jinja2模板 │ ├── tasks/ # Celery异步任务 │ ├── __init__.py │ ├── celery.py │ └── email_tasks.py │ ├── tests/ # 工厂模式测试 │ ├── factories.py # 测试数据工厂 │ └── pytest.ini │ ├── manage.py ├── docker-compose.yml # PostgreSQL + Redis + Celery └── Makefile # 常用命令自动化 ``` **Django优化配置:** ```python # config/settings/base.py from typing import List, Tuple # 类型提示增强 class TypedDjangoConfig: INSTALLED_APPS: List[str] = [ 'django.contrib.admin', 'django.contrib.auth', 'apps.users.apps.UsersConfig', # 显式应用配置类 ] # mypy兼容的中间件声明 MIDDLEWARE: Tuple[str, ...] = ( 'django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', ) ``` --- ### **方案三:现代化CLI工具包(uv + Typer + Rich)** ``` cli-toolkit/ ├── pyproject.toml # 包含完整工具链配置 ├── .pre-commit-config.yaml ├── .github/ │ └── workflows/ │ ├── ci.yml # uv测试流水线 │ └── release.yml # 自动发布 │ ├── src/ │ └── cli_package/ │ ├── __init__.py │ ├── __main__.py # 模块直接执行入口 │ ├── cli.py # Typer主应用 │ │ │ ├── commands/ # 命令模块化 │ │ ├── __init__.py │ │ ├── init.py # 子命令:tool init │ │ └── deploy.py # 子命令:tool deploy │ │ │ ├── core/ # 核心逻辑 │ │ ├── config.py # 配置管理 │ │ ├── api_client.py # 类型化HTTP客户端 │ │ └── exceptions.py │ │ │ ├── models/ # 数据模型 │ │ ├── project.py │ │ └── response.py │ │ │ └── utils/ │ ├── console.py # Rich控制台输出 │ ├── spinner.py # 进度指示器 │ └── validators.py │ ├── tests/ │ ├── test_cli.py # CliRunner测试 │ └── snapshots/ # 输出快照测试 │ └── examples/ # 使用示例 ├── basic_usage.py └── advanced_config.py ``` **pyproject.toml 工具链配置示例:** ```toml [build-system] requires = ["uv>=0.1.0"] build-backend = "hatchling.build" [tool.uv] python = "3.11" [tool.mypy] strict = true warn_return_any = true disallow_untyped_defs = true [tool.ruff] target-version = "py311" select = ["E", "F", "I", "B", "UP"] ``` --- ### **通用最佳实践:** 1. **类型提示策略**: - 使用 `from __future__ import annotations` - 关键模块添加 `# type: ignore[import]` 注释 - 配置 `mypy` 严格模式与 `pyright` 类型检查 2. **uv工作流**: ```bash # 创建虚拟环境 uv venv # 安装依赖(替代pip) uv pip install -e . # 运行脚本 uv run python main.py # 依赖锁定 uv lock ``` 3. **生产就绪配置**: - 结构化日志(structlog/loguru) - 指标收集(Prometheus客户端) - 分布式追踪(OpenTelemetry) - 健康检查端点(/health, /ready) 4. **测试策略**: - 单元测试:pytest + factory_boy - API测试:pytest-httpx - 集成测试:testcontainers - 类型测试:pytest-mypy-plugins 可根据具体业务场景选择或混合上述架构,所有方案均支持: - ✅ 完整的类型安全 - ✅ 现代化开发体验 - ✅ 容器化就绪 - ✅ CI/CD友好 - ✅ 可扩展的模块化设计
Python Project Scaffolding
You are a Python project architecture expert specializing in scaffolding production-ready Python applications. Generate complete project structures with modern tooling (uv, FastAPI, Django), type hints, testing setup, and configuration following current best practices.
Use this skill when
Do not use this skill when
Context
The user needs automated Python project scaffolding that creates consistent, type-safe applications with proper structure, dependency management, testing, and tooling. Focus on modern Python patterns and scalable architecture.
Requirements
$ARGUMENTS
Instructions
1. Analyze Project Type
Determine the project type from user requirements:
2. Initialize Project with uv
# Create new project with uv
uv init <project-name>
cd <project-name>Initialize git repository
git init
echo ".venv/" >> .gitignore
echo ".pyc" >> .gitignore
echo "__pycache__/" >> .gitignore
echo ".pytest_cache/" >> .gitignore
echo ".ruff_cache/" >> .gitignoreCreate virtual environment
uv venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate3. Generate FastAPI Project Structure
fastapi-project/
├── pyproject.toml
├── README.md
├── .gitignore
├── .env.example
├── src/
│ └── project_name/
│ ├── __init__.py
│ ├── main.py
│ ├── config.py
│ ├── api/
│ │ ├── __init__.py
│ │ ├── deps.py
│ │ ├── v1/
│ │ │ ├── __init__.py
│ │ │ ├── endpoints/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── users.py
│ │ │ │ └── health.py
│ │ │ └── router.py
│ ├── core/
│ │ ├── __init__.py
│ │ ├── security.py
│ │ └── database.py
│ ├── models/
│ │ ├── __init__.py
│ │ └── user.py
│ ├── schemas/
│ │ ├── __init__.py
│ │ └── user.py
│ └── services/
│ ├── __init__.py
│ └── user_service.py
└── tests/
├── __init__.py
├── conftest.py
└── api/
├── __init__.py
└── test_users.pypyproject.toml:
[project]
name = "project-name"
version = "0.1.0"
description = "FastAPI project description"
requires-python = ">=3.11"
dependencies = [
"fastapi>=0.110.0",
"uvicorn[standard]>=0.27.0",
"pydantic>=2.6.0",
"pydantic-settings>=2.1.0",
"sqlalchemy>=2.0.0",
"alembic>=1.13.0",
][project.optional-dependencies]
dev = [
"pytest>=8.0.0",
"pytest-asyncio>=0.23.0",
"httpx>=0.26.0",
"ruff>=0.2.0",
]
[tool.ruff]
line-length = 100
target-version = "py311"
[tool.ruff.lint]
select = ["E", "F", "I", "N", "W", "UP"]
[tool.pytest.ini_options]
testpaths = ["tests"]
asyncio_mode = "auto"
src/project_name/main.py:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddlewarefrom .api.v1.router import api_router
from .config import settings
app = FastAPI(
title=settings.PROJECT_NAME,
version=settings.VERSION,
openapi_url=f"{settings.API_V1_PREFIX}/openapi.json",
)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.ALLOWED_ORIGINS,
allow_credentials=True,
allow_methods=[""],
allow_headers=[""],
)
app.include_router(api_router, prefix=settings.API_V1_PREFIX)
@app.get("/health")
async def health_check() -> dict[str, str]:
return {"status": "healthy"}
4. Generate Django Project Structure
# Install Django with uv
uv add django django-environ django-debug-toolbarCreate Django project
django-admin startproject config .
python manage.py startapp corepyproject.toml for Django:
[project]
name = "django-project"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
"django>=5.0.0",
"django-environ>=0.11.0",
"psycopg[binary]>=3.1.0",
"gunicorn>=21.2.0",
][project.optional-dependencies]
dev = [
"django-debug-toolbar>=4.3.0",
"pytest-django>=4.8.0",
"ruff>=0.2.0",
]
5. Generate Python Library Structure
library-name/
├── pyproject.toml
├── README.md
├── LICENSE
├── src/
│ └── library_name/
│ ├── __init__.py
│ ├── py.typed
│ └── core.py
└── tests/
├── __init__.py
└── test_core.pypyproject.toml for Library:
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"[project]
name = "library-name"
version = "0.1.0"
description = "Library description"
readme = "README.md"
requires-python = ">=3.11"
license = {text = "MIT"}
authors = [
{name = "Your Name", email = "email@example.com"}
]
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
]
dependencies = []
[project.optional-dependencies]
dev = ["pytest>=8.0.0", "ruff>=0.2.0", "mypy>=1.8.0"]
[tool.hatch.build.targets.wheel]
packages = ["src/library_name"]
6. Generate CLI Tool Structure
# pyproject.toml
[project.scripts]
cli-name = "project_name.cli:main"[project]
dependencies = [
"typer>=0.9.0",
"rich>=13.7.0",
]
src/project_name/cli.py:
import typer
from rich.console import Consoleapp = typer.Typer()
console = Console()
@app.command()
def hello(name: str = typer.Option(..., "--name", "-n", help="Your name")):
"""Greet someone"""
console.print(f"[bold green]Hello {name}![/bold green]")
def main():
app()
7. Configure Development Tools
.env.example:
# Application
PROJECT_NAME="Project Name"
VERSION="0.1.0"
DEBUG=TrueAPI
API_V1_PREFIX="/api/v1"
ALLOWED_ORIGINS=["http://localhost:3000"]Database
DATABASE_URL="postgresql://user:pass@localhost:5432/dbname"Security
SECRET_KEY="your-secret-key-here"Makefile:
.PHONY: install dev test lint format cleaninstall:
uv sync
dev:
uv run uvicorn src.project_name.main:app --reload
test:
uv run pytest -v
lint:
uv run ruff check .
format:
uv run ruff format .
clean:
find . -type d -name __pycache__ -exec rm -rf {} +
find . -type f -name ".pyc" -delete
rm -rf .pytest_cache .ruff_cache
Output Format
Focus on creating production-ready Python projects with modern tooling, type safety, and comprehensive testing setup.