example-framework-skill
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseExample Framework Skill
Example Framework Skill
A complete example demonstrating proper self-containment patterns for Claude Code skills.
When to Use: Building applications with Example Framework - includes setup, patterns, testing, and deployment.
这是一个完整的示例,展示了Claude Code skill的规范自包含模式。
适用场景:使用Example Framework构建应用,涵盖配置、模式、测试和部署全流程。
Overview
概述
This skill demonstrates the correct approach to self-contained skill development:
✅ Self-Contained: All essential content inlined - works standalone
✅ No Dependencies: No relative paths to other skills
✅ Complete Examples: Working code, not fragments
✅ Graceful Degradation: Notes optional enhancements without requiring them
✅ Flat Deployment Ready: Works in any directory structure
本skill展示了自包含skill开发的正确方案:
✅ 自包含:所有核心内容均内置,可独立运行
✅ 无依赖:没有指向其他skill的相对路径
✅ 示例完整:提供可运行的完整代码,而非代码片段
✅ 优雅降级:标注可选增强功能但不强制依赖
✅ 扁平化部署就绪:可在任意目录结构下运行
Quick Start
快速开始
Installation
安装
bash
undefinedbash
undefinedInstall framework
Install framework
pip install example-framework
pip install example-framework
Create new project
Create new project
example-framework init my-project
cd my-project
example-framework init my-project
cd my-project
Install dependencies
Install dependencies
pip install -r requirements.txt
pip install -r requirements.txt
Run development server
Run development server
example-framework dev
undefinedexample-framework dev
undefinedMinimal Example (Self-Contained)
最小示例(自包含)
python
"""
Minimal Example Framework application.
Self-contained - no external skill dependencies.
"""
from example_framework import App, route
app = App()
@route("/")
def home():
"""Homepage route."""
return {"message": "Hello, World!"}
@route("/users/{user_id}")
def get_user(user_id: int):
"""Get user by ID."""
return {
"id": user_id,
"username": f"user_{user_id}"
}
if __name__ == "__main__":
# Development server
app.run(host="0.0.0.0", port=8000, debug=True)Run it:
bash
python app.pypython
"""
Minimal Example Framework application.
Self-contained - no external skill dependencies.
"""
from example_framework import App, route
app = App()
@route("/")
def home():
"""Homepage route."""
return {"message": "Hello, World!"}
@route("/users/{user_id}")
def get_user(user_id: int):
"""Get user by ID."""
return {
"id": user_id,
"username": f"user_{user_id}"
}
if __name__ == "__main__":
# Development server
app.run(host="0.0.0.0", port=8000, debug=True)运行方式:
bash
python app.pyVisit: http://localhost:8000
访问地址: http://localhost:8000
---
---Core Patterns
核心模式
1. Application Setup (Self-Contained)
1. 应用配置(自包含)
Complete setup pattern - no external dependencies:
python
from example_framework import App, Config
from example_framework.middleware import CORSMiddleware, LoggingMiddleware完整配置模式 - 无外部依赖:
python
from example_framework import App, Config
from example_framework.middleware import CORSMiddleware, LoggingMiddlewareConfiguration
Configuration
config = Config(
DEBUG=True,
SECRET_KEY="your-secret-key-here",
DATABASE_URL="sqlite:///./app.db"
)
config = Config(
DEBUG=True,
SECRET_KEY="your-secret-key-here",
DATABASE_URL="sqlite:///./app.db"
)
Application instance
Application instance
app = App(config=config)
app = App(config=config)
Middleware
Middleware
app.add_middleware(
CORSMiddleware,
allow_origins=[""],
allow_methods=[""],
allow_headers=["*"]
)
app.add_middleware(LoggingMiddleware)
app.add_middleware(
CORSMiddleware,
allow_origins=[""],
allow_methods=[""],
allow_headers=["*"]
)
app.add_middleware(LoggingMiddleware)
Health check endpoint
Health check endpoint
@app.route("/health")
def health_check():
"""Health check endpoint."""
return {"status": "healthy"}
undefined@app.route("/health")
def health_check():
"""Health check endpoint."""
return {"status": "healthy"}
undefined2. Database Integration (Self-Contained)
2. 数据库集成(自包含)
Essential database pattern - inlined for self-containment:
python
from example_framework import Database
from contextlib import contextmanager核心数据库模式 - 内置实现保证自包含:
python
from example_framework import Database
from contextlib import contextmanagerDatabase configuration
Database configuration
db = Database("sqlite:///./app.db")
@contextmanager
def get_db_session():
"""
Database session context manager.
Usage:
with get_db_session() as session:
users = session.query(User).all()
"""
session = db.create_session()
try:
yield session
session.commit()
except Exception:
session.rollback()
raise
finally:
session.close()db = Database("sqlite:///./app.db")
@contextmanager
def get_db_session():
"""
Database session context manager.
Usage:
with get_db_session() as session:
users = session.query(User).all()
"""
session = db.create_session()
try:
yield session
session.commit()
except Exception:
session.rollback()
raise
finally:
session.close()Model example
Model example
class User(db.Model):
tablename = "users"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def to_dict(self):
"""Convert to dictionary."""
return {
"id": self.id,
"username": self.username,
"email": self.email
}class User(db.Model):
tablename = "users"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def to_dict(self):
"""Convert to dictionary."""
return {
"id": self.id,
"username": self.username,
"email": self.email
}CRUD operations
CRUD operations
@app.route("/users", methods=["POST"])
def create_user(data):
"""Create new user."""
with get_db_session() as session:
user = User(
username=data["username"],
email=data["email"]
)
session.add(user)
return user.to_dict(), 201
@app.route("/users/{user_id}")
def get_user(user_id: int):
"""Get user by ID."""
with get_db_session() as session:
user = session.query(User).filter_by(id=user_id).first()
if not user:
return {"error": "User not found"}, 404
return user.to_dict()
undefined@app.route("/users", methods=["POST"])
def create_user(data):
"""Create new user."""
with get_db_session() as session:
user = User(
username=data["username"],
email=data["email"]
)
session.add(user)
return user.to_dict(), 201
@app.route("/users/{user_id}")
def get_user(user_id: int):
"""Get user by ID."""
with get_db_session() as session:
user = session.query(User).filter_by(id=user_id).first()
if not user:
return {"error": "User not found"}, 404
return user.to_dict()
undefined3. Testing Pattern (Self-Contained)
3. 测试模式(自包含)
Essential testing patterns - inlined from testing best practices:
python
"""
Test suite for Example Framework application.
Self-contained testing patterns - no external skill dependencies.
"""
import pytest
from example_framework.testing import TestClient核心测试模式 - 基于测试最佳实践内置实现:
python
"""
Test suite for Example Framework application.
Self-contained testing patterns - no external skill dependencies.
"""
import pytest
from example_framework.testing import TestClientTest client fixture
Test client fixture
@pytest.fixture
def client():
"""Create test client."""
return TestClient(app)
@pytest.fixture
def client():
"""Create test client."""
return TestClient(app)
Database fixture
Database fixture
@pytest.fixture
def db_session():
"""Create test database session."""
db.create_all()
session = db.create_session()
yield session
session.close()
db.drop_all()
@pytest.fixture
def db_session():
"""Create test database session."""
db.create_all()
session = db.create_session()
yield session
session.close()
db.drop_all()
Test examples
Test examples
def test_home_route(client):
"""Test homepage returns correct response."""
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "Hello, World!"}
def test_create_user(client, db_session):
"""Test user creation."""
response = client.post("/users", json={
"username": "testuser",
"email": "test@example.com"
})
assert response.status_code == 201
data = response.json()
assert data["username"] == "testuser"
assert data["email"] == "test@example.com"
def test_get_user(client, db_session):
"""Test get user by ID."""
# Create user
user = User(username="testuser", email="test@example.com")
db_session.add(user)
db_session.commit()
# Get user
response = client.get(f"/users/{user.id}")
assert response.status_code == 200
assert response.json()["username"] == "testuser"def test_user_not_found(client):
"""Test 404 for nonexistent user."""
response = client.get("/users/999")
assert response.status_code == 404
**Run tests:**
```bash
pytest tests/def test_home_route(client):
"""Test homepage returns correct response."""
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "Hello, World!"}
def test_create_user(client, db_session):
"""Test user creation."""
response = client.post("/users", json={
"username": "testuser",
"email": "test@example.com"
})
assert response.status_code == 201
data = response.json()
assert data["username"] == "testuser"
assert data["email"] == "test@example.com"
def test_get_user(client, db_session):
"""Test get user by ID."""
# Create user
user = User(username="testuser", email="test@example.com")
db_session.add(user)
db_session.commit()
# Get user
response = client.get(f"/users/{user.id}")
assert response.status_code == 200
assert response.json()["username"] == "testuser"def test_user_not_found(client):
"""Test 404 for nonexistent user."""
response = client.get("/users/999")
assert response.status_code == 404
**运行测试:**
```bash
pytest tests/Error Handling
错误处理
Standard Error Handler Pattern (Self-Contained)
标准错误处理器模式(自包含)
python
from example_framework import HTTPException
@app.error_handler(404)
def not_found_handler(error):
"""Handle 404 errors."""
return {
"error": "Not Found",
"message": str(error)
}, 404
@app.error_handler(500)
def server_error_handler(error):
"""Handle 500 errors."""
return {
"error": "Internal Server Error",
"message": "An unexpected error occurred"
}, 500
@app.error_handler(HTTPException)
def http_exception_handler(error):
"""Handle HTTP exceptions."""
return {
"error": error.name,
"message": error.description
}, error.status_codepython
from example_framework import HTTPException
@app.error_handler(404)
def not_found_handler(error):
"""Handle 404 errors."""
return {
"error": "Not Found",
"message": str(error)
}, 404
@app.error_handler(500)
def server_error_handler(error):
"""Handle 500 errors."""
return {
"error": "Internal Server Error",
"message": "An unexpected error occurred"
}, 500
@app.error_handler(HTTPException)
def http_exception_handler(error):
"""Handle HTTP exceptions."""
return {
"error": error.name,
"message": error.description
}, error.status_codeCustom validation error
Custom validation error
class ValidationError(Exception):
"""Validation error."""
pass
@app.error_handler(ValidationError)
def validation_error_handler(error):
"""Handle validation errors."""
return {
"error": "Validation Error",
"message": str(error)
}, 400
---class ValidationError(Exception):
"""Validation error."""
pass
@app.error_handler(ValidationError)
def validation_error_handler(error):
"""Handle validation errors."""
return {
"error": "Validation Error",
"message": str(error)
}, 400
---Best Practices
最佳实践
1. Configuration Management
1. 配置管理
python
undefinedpython
undefinedenvironment-based configuration
environment-based configuration
import os
from example_framework import Config
class DevelopmentConfig(Config):
DEBUG = True
DATABASE_URL = "sqlite:///./dev.db"
class ProductionConfig(Config):
DEBUG = False
DATABASE_URL = os.getenv("DATABASE_URL")
SECRET_KEY = os.getenv("SECRET_KEY")
import os
from example_framework import Config
class DevelopmentConfig(Config):
DEBUG = True
DATABASE_URL = "sqlite:///./dev.db"
class ProductionConfig(Config):
DEBUG = False
DATABASE_URL = os.getenv("DATABASE_URL")
SECRET_KEY = os.getenv("SECRET_KEY")
Load config based on environment
Load config based on environment
env = os.getenv("ENV", "development")
config = DevelopmentConfig() if env == "development" else ProductionConfig()
app = App(config=config)
undefinedenv = os.getenv("ENV", "development")
config = DevelopmentConfig() if env == "development" else ProductionConfig()
app = App(config=config)
undefined2. Dependency Injection
2. 依赖注入
python
undefinedpython
undefinedDependency injection pattern
Dependency injection pattern
from example_framework import Depends
def get_current_user(token: str = Depends("Authorization")):
"""Get current user from token."""
# Token validation logic
user_id = validate_token(token)
return User.query.get(user_id)
@app.route("/profile")
def get_profile(user: User = Depends(get_current_user)):
"""Get current user profile."""
return user.to_dict()
undefinedfrom example_framework import Depends
def get_current_user(token: str = Depends("Authorization")):
"""Get current user from token."""
# Token validation logic
user_id = validate_token(token)
return User.query.get(user_id)
@app.route("/profile")
def get_profile(user: User = Depends(get_current_user)):
"""Get current user profile."""
return user.to_dict()
undefined3. Request Validation
3. 请求校验
python
from example_framework import validate_requestpython
from example_framework import validate_requestRequest schema
Request schema
user_schema = {
"username": {"type": "string", "minLength": 3, "maxLength": 80},
"email": {"type": "string", "format": "email"},
"age": {"type": "integer", "minimum": 0}
}
@app.route("/users", methods=["POST"])
@validate_request(user_schema)
def create_user(data):
"""Create user with validated data."""
# Data is already validated
user = User(**data)
db.session.add(user)
db.session.commit()
return user.to_dict(), 201
---user_schema = {
"username": {"type": "string", "minLength": 3, "maxLength": 80},
"email": {"type": "string", "format": "email"},
"age": {"type": "integer", "minimum": 0}
}
@app.route("/users", methods=["POST"])
@validate_request(user_schema)
def create_user(data):
"""Create user with validated data."""
# Data is already validated
user = User(**data)
db.session.add(user)
db.session.commit()
return user.to_dict(), 201
---Deployment
部署
Production Deployment (Self-Contained)
生产环境部署(自包含)
python
"""
Production deployment configuration.
Self-contained - all necessary patterns included.
"""python
"""
Production deployment configuration.
Self-contained - all necessary patterns included.
"""1. Use production server (e.g., gunicorn)
1. Use production server (e.g., gunicorn)
requirements.txt:
requirements.txt:
gunicorn>=20.1.0
gunicorn>=20.1.0
2. Production configuration
2. Production configuration
import os
class ProductionConfig:
DEBUG = False
TESTING = False
SECRET_KEY = os.getenv("SECRET_KEY")
DATABASE_URL = os.getenv("DATABASE_URL")
ALLOWED_HOSTS = os.getenv("ALLOWED_HOSTS", "").split(",")
app = App(config=ProductionConfig())
import os
class ProductionConfig:
DEBUG = False
TESTING = False
SECRET_KEY = os.getenv("SECRET_KEY")
DATABASE_URL = os.getenv("DATABASE_URL")
ALLOWED_HOSTS = os.getenv("ALLOWED_HOSTS", "").split(",")
app = App(config=ProductionConfig())
3. Run with gunicorn
3. Run with gunicorn
gunicorn -w 4 -b 0.0.0.0:8000 app:app
gunicorn -w 4 -b 0.0.0.0:8000 app:app
4. Environment variables (.env)
4. Environment variables (.env)
SECRET_KEY=your-production-secret-key
SECRET_KEY=your-production-secret-key
DATABASE_URL=postgresql://user:pass@localhost/dbname
DATABASE_URL=postgresql://user:pass@localhost/dbname
ALLOWED_HOSTS=example.com,www.example.com
ALLOWED_HOSTS=example.com,www.example.com
---
---Complementary Skills
配套Skill
When using this skill, consider these related skills (if deployed):
-
pytest-patterns: Advanced testing patterns and fixtures
- Use case: Comprehensive test suites with parametrization
- Integration: Enhance basic testing patterns shown above
- Status: Optional - basic testing patterns included in this skill
-
database-orm-patterns: Advanced ORM patterns and optimization
- Use case: Complex queries, relationships, performance tuning
- Integration: Builds on basic database pattern shown above
- Status: Optional - basic CRUD patterns included in this skill
-
api-security: Authentication, authorization, security best practices
- Use case: Production-ready security implementation
- Integration: Adds security layer to routes
- Status: Recommended for production - basic examples shown above
-
deployment-patterns: Docker, CI/CD, monitoring, scaling
- Use case: Production deployment and operations
- Integration: Deployment strategies and tooling
- Status: Optional - basic deployment shown above
Note: All complementary skills are independently deployable. This skill is fully functional without them.
使用本skill时,可考虑搭配以下相关skill(如果已部署):
-
pytest-patterns: 高级测试模式和fixture
- 适用场景:带参数化的全面测试套件
- 集成方式:扩展本文展示的基础测试模式
- 状态:可选 - 本skill已包含基础测试模式
-
database-orm-patterns: 高级ORM模式和优化方案
- 适用场景:复杂查询、表关系、性能调优
- 集成方式:在本文展示的基础数据库模式上扩展
- 状态:可选 - 本skill已包含基础CRUD模式
-
api-security: 认证、授权、安全最佳实践
- 适用场景:生产级安全实现
- 集成方式:为路由添加安全层
- 状态:生产环境推荐使用 - 本文仅展示基础示例
-
deployment-patterns: Docker、CI/CD、监控、扩缩容
- 适用场景:生产部署和运维
- 集成方式:提供部署策略和工具支持
- 状态:可选 - 本skill已包含基础部署方案
注意:所有配套skill均可独立部署。无需依赖这些skill,本skill即可完全正常运行。
Common Pitfalls
常见误区
❌ Don't: Relative Imports
❌ 禁止:相对导入
python
undefinedpython
undefinedDON'T DO THIS
请勿这么写
from ..other_skill.patterns import setup
undefinedfrom ..other_skill.patterns import setup
undefined✅ Do: Self-Contained Patterns
✅ 推荐:自包含模式
python
undefinedpython
undefinedInclude pattern directly
直接内置实现模式
def setup():
"""Setup pattern (self-contained)."""
# Implementation here
pass
undefineddef setup():
"""Setup pattern (self-contained)."""
# 实现代码
pass
undefined❌ Don't: External Skill Dependencies
❌ 禁止:外部Skill依赖
python
undefinedpython
undefinedDON'T DO THIS
请勿这么写
This requires pytest-patterns skill
该代码依赖pytest-patterns skill
from skills.pytest_patterns import fixture_factory
undefinedfrom skills.pytest_patterns import fixture_factory
undefined✅ Do: Inline Essential Patterns
✅ 推荐:内置核心模式
python
undefinedpython
undefinedInclude essential pattern
内置核心模式实现
def fixture_factory(name, default=None):
"""Fixture factory pattern (inlined)."""
@pytest.fixture
def _fixture():
return default
_fixture.name = name
return _fixture
---def fixture_factory(name, default=None):
"""Fixture factory pattern (inlined)."""
@pytest.fixture
def _fixture():
return default
_fixture.name = name
return _fixture
---Progressive Disclosure
进阶内容指引
For more advanced topics, see the directory:
references/- references/advanced-patterns.md: Advanced framework patterns
- references/performance.md: Performance optimization
- references/api-reference.md: Complete API documentation
Note: Main SKILL.md is self-sufficient. References provide optional deep dives.
如需了解更高级的主题,可查看目录:
references/- references/advanced-patterns.md: 高级框架模式
- references/performance.md: 性能优化
- references/api-reference.md: 完整API文档
注意:主SKILL.md文件内容已足够独立使用。参考文档仅提供可选的深入解析。
Resources
资源
Official Documentation:
- Example Framework Docs: https://example-framework.readthedocs.io
- API Reference: https://example-framework.readthedocs.io/api
- Community: https://github.com/example-framework/community
Related Technologies:
- Python: https://docs.python.org
- SQLite: https://www.sqlite.org
- Pytest: https://docs.pytest.org
官方文档:
- Example Framework 文档: https://example-framework.readthedocs.io
- API 参考: https://example-framework.readthedocs.io/api
- 社区: https://github.com/example-framework/community
相关技术:
- Python: https://docs.python.org
- SQLite: https://www.sqlite.org
- Pytest: https://docs.pytest.org
Summary
总结
This skill demonstrates self-contained skill development:
✅ Complete: All essential patterns included inline
✅ Independent: Works without other skills
✅ Tested: Verified in isolation
✅ Deployable: Works in flat directory structure
✅ Graceful: Notes optional enhancements without requiring them
Use this as a template for creating new skills.
Version: 1.0.0
Last Updated: 2025-11-30
Self-Containment: ✅ Fully Compliant
本skill展示了自包含skill开发规范:
✅ 完整:所有核心模式均内置实现
✅ 独立:无需依赖其他skill即可运行
✅ 可测试:可单独验证功能
✅ 可部署:可在扁平化目录结构下运行
✅ 可扩展:标注可选增强功能但不强制依赖
可将本skill作为模板创建新的skill。
版本: 1.0.0
最后更新: 2025-11-30
自包含合规性: ✅ 完全符合要求