From d9873219d638ca5c6e6710e0796c389aa665d809 Mon Sep 17 00:00:00 2001 From: gao Date: Thu, 27 Nov 2025 21:17:46 +0800 Subject: [PATCH] init template --- .gitignore | 44 +++- TEMPLATE_GUIDE.md | 459 +++++++++++++++++++++++++++++++++++ TEMPLATE_QUICK_START.md | 288 ++++++++++++++++++++++ backend/.env.example | 179 +++++++++++++- create-from-template.sh | 513 ++++++++++++++++++++++++++++++++++++++++ template.config.json | 114 +++++++++ 6 files changed, 1585 insertions(+), 12 deletions(-) create mode 100644 TEMPLATE_GUIDE.md create mode 100644 TEMPLATE_QUICK_START.md create mode 100755 create-from-template.sh create mode 100644 template.config.json diff --git a/.gitignore b/.gitignore index 5bc4d46..c225f6b 100644 --- a/.gitignore +++ b/.gitignore @@ -65,5 +65,45 @@ temp/ .DS_Store Thumbs.db -# Git temporary files -.git/ \ No newline at end of file +# Coverage reports +htmlcov/ +.coverage +.coverage.* +coverage.xml +*.cover +.pytest_cache/ + +# Docker +docker-compose.override.yml +.dockerignore + +# Frontend specific +.cache/ +.parcel-cache/ +.next/ +.nuxt/ +.vuepress/dist + +# Testing +.tox/ +.nox/ + +# MyPy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# Certificates and keys +*.pem +*.key +*.crt + +# Local configuration +config.local.js +config.local.json \ No newline at end of file diff --git a/TEMPLATE_GUIDE.md b/TEMPLATE_GUIDE.md new file mode 100644 index 0000000..4c3c02f --- /dev/null +++ b/TEMPLATE_GUIDE.md @@ -0,0 +1,459 @@ +# 项目模板使用指南 + +## 概述 + +这是一个生产级的 FastAPI + Vue 3 全栈应用模板,包含完整的用户认证、文件上传、数据库操作和现代化前端界面。 + +## 模板特性 + +### 后端 (FastAPI) +- ✅ RESTful API 设计 +- ✅ JWT 身份认证 +- ✅ SQLAlchemy ORM (支持 PostgreSQL/SQLite) +- ✅ 文件上传处理 +- ✅ PDF 处理能力 +- ✅ AI 模型集成 (Claude, Gemini) +- ✅ 自动 API 文档 (Swagger/OpenAPI) +- ✅ CORS 配置 +- ✅ 环境变量管理 + +### 前端 (Vue 3) +- ✅ Composition API +- ✅ Element Plus UI 组件库 +- ✅ Pinia 状态管理 +- ✅ Vue Router 路由 +- ✅ Vite 构建工具 +- ✅ 响应式设计 +- ✅ 统一配置管理 +- ✅ API 服务封装 + +## 快速开始 + +### 方法一: 使用自动化脚本 (推荐) + +```bash +# 1. 运行创建脚本 +./create-from-template.sh + +# 2. 根据提示输入项目信息 +Project name: my-awesome-app +Display name: My Awesome App +Database name: myapp_db +API port: 8888 +Frontend port: 3000 + +# 3. 脚本会自动: +# - 创建新项目目录 +# - 复制所有文件 +# - 替换配置项 +# - 清理临时文件 +# - 初始化 git 仓库 +``` + +### 方法二: 手动创建 + +#### 1. 复制项目 + +```bash +# 复制整个项目到新目录 +cp -r /path/to/pager /path/to/your-new-project +cd /path/to/your-new-project + +# 清理不需要的文件 +rm -rf .git backend/__pycache__ backend/wordmaster.db backend/uploads/* frontend/node_modules frontend/dist +``` + +#### 2. 配置后端 + +```bash +cd backend + +# 复制环境变量配置 +cp .env.example .env + +# 编辑 .env 文件,修改以下配置: +# - DATABASE_URL: 数据库连接字符串 +# - SECRET_KEY: JWT 密钥 (必须修改!) +# - OPENROUTER_API_KEY: AI API 密钥 (如需要) +# - AI_MODEL: AI 模型选择 + +# 安装依赖 +pip install -r requirements.txt + +# 初始化数据库 +python main.py +``` + +#### 3. 配置前端 + +```bash +cd frontend + +# 编辑 package.json +# 修改 "name": "your-project-frontend" + +# 安装依赖 +npm install + +# 配置开发环境变量 (可选) +# 编辑 .env.development +# VITE_API_BASE_URL=http://localhost:8888/api +``` + +#### 4. 修改项目名称和品牌 + +需要修改的文件: + +**后端:** +- `backend/main.py`: 数据库名称、应用描述 +- `backend/.env`: 数据库连接字符串 + +**前端:** +- `frontend/package.json`: 项目名称 +- `frontend/index.html`: 页面标题 +- `frontend/src/config/index.js`: API 端口配置 + +#### 5. 启动项目 + +```bash +# 后端 (在 backend 目录) +python main.py +# 或 +uvicorn main:app --host 0.0.0.0 --port 8888 --reload + +# 前端 (在 frontend 目录) +npm run dev +``` + +## 项目结构详解 + +``` +your-project/ +├── backend/ # FastAPI 后端 +│ ├── main.py # 主应用文件 (所有 API 端点) +│ ├── requirements.txt # Python 依赖 +│ ├── .env.example # 环境变量示例 +│ ├── migrate_db.py # 数据库迁移脚本 +│ ├── pdf_splitter_*.py # PDF 处理模块 +│ ├── claude_exam_parser.py # AI 解析器 +│ ├── utils/ # 工具函数 +│ └── uploads/ # 文件上传目录 +│ +├── frontend/ # Vue 3 前端 +│ ├── src/ +│ │ ├── main.js # 应用入口 +│ │ ├── App.vue # 根组件 +│ │ ├── router/ # 路由配置 +│ │ ├── stores/ # Pinia 状态管理 +│ │ ├── views/ # 页面组件 +│ │ ├── components/ # 可复用组件 +│ │ ├── config/ # 配置管理 +│ │ └── services/ # API 服务 +│ ├── package.json # 前端依赖 +│ └── vite.config.js # Vite 配置 +│ +├── start.sh # 开发启动脚本 +├── stop.sh # 停止脚本 +├── status.sh # 状态检查脚本 +├── template.config.json # 模板配置 +└── TEMPLATE_GUIDE.md # 本文档 +``` + +## 核心功能模块 + +### 1. 用户认证系统 + +**后端实现** (`backend/main.py`): +```python +# 注册 +@app.post("/api/auth/register") + +# 登录 +@app.post("/api/auth/login") + +# 获取当前用户 +def get_current_user(credentials: HTTPAuthorizationCredentials) +``` + +**前端实现** (`frontend/src/stores/auth.js`): +```javascript +// 登录 +async login(username, password) + +// 注册 +async register(username, password) + +// 登出 +logout() + +// 自动加载用户信息 +loadUser() +``` + +### 2. 数据库模型 + +**基础模型结构** (`backend/main.py`): +```python +class User(Base): + __tablename__ = "users" + id = Column(Integer, primary_key=True) + username = Column(String, unique=True) + password_hash = Column(String) + created_at = Column(DateTime) + +# 添加你自己的模型 +class YourModel(Base): + __tablename__ = "your_table" + # 定义字段... +``` + +### 3. 文件上传 + +**后端示例**: +```python +@app.post("/api/upload") +async def upload_file( + file: UploadFile = File(...), + current_user: User = Depends(get_current_user) +): + # 保存到 uploads/{user_id}/ + file_path = f"uploads/{current_user.id}/{file.filename}" + # 处理文件... + return {"file_path": file_path} +``` + +**前端示例** (使用 Element Plus): +```vue + + 上传文件 + +``` + +### 4. 状态管理 (Pinia) + +创建新的 store (`frontend/src/stores/yourStore.js`): +```javascript +import { defineStore } from 'pinia' +import { ref } from 'vue' + +export const useYourStore = defineStore('your-store', () => { + const data = ref([]) + + async function fetchData() { + // API 调用... + } + + return { data, fetchData } +}) +``` + +### 5. 路由配置 + +添加新路由 (`frontend/src/router/index.js`): +```javascript +{ + path: '/your-page', + name: 'YourPage', + component: () => import('../views/YourPage.vue'), + meta: { requiresAuth: true } // 需要登录 +} +``` + +## 自定义和扩展 + +### 添加新的 API 端点 + +在 `backend/main.py` 中: +```python +@app.get("/api/your-endpoint") +async def your_endpoint( + current_user: User = Depends(get_current_user), + db: Session = Depends(get_db) +): + # 你的逻辑 + return {"data": "your data"} +``` + +### 添加新的前端页面 + +1. 创建组件: `frontend/src/views/YourPage.vue` +```vue + + + +``` + +2. 在路由中注册 (见上面路由配置) + +### 修改数据库模型 + +1. 编辑 `backend/main.py` 中的模型定义 +2. 运行迁移: +```bash +cd backend +python migrate_db.py +``` + +## 部署指南 + +### 环境变量配置 + +**生产环境必须修改**: +```bash +# backend/.env +SECRET_KEY=your-very-long-random-secret-key-min-32-chars +DATABASE_URL=postgresql://user:password@host:port/dbname +``` + +### Docker 部署 + +创建 `Dockerfile` (后端): +```dockerfile +FROM python:3.9-slim +WORKDIR /app +COPY requirements.txt . +RUN pip install -r requirements.txt +COPY . . +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8888"] +``` + +创建 `Dockerfile` (前端): +```dockerfile +FROM node:18-alpine +WORKDIR /app +COPY package*.json ./ +RUN npm install +COPY . . +RUN npm run build +CMD ["npm", "run", "preview"] +``` + +### Nginx 配置 + +```nginx +server { + listen 80; + server_name your-domain.com; + + location / { + root /var/www/frontend/dist; + try_files $uri $uri/ /index.html; + } + + location /api { + proxy_pass http://localhost:8888; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + } +} +``` + +## 最佳实践 + +### 1. 安全性 +- ✅ 修改默认 SECRET_KEY +- ✅ 使用 HTTPS (生产环境) +- ✅ 限制 CORS 源 +- ✅ 定期更新依赖 +- ✅ 不要提交 .env 文件 + +### 2. 性能优化 +- ✅ 启用数据库索引 +- ✅ 使用连接池 +- ✅ 前端代码分割 +- ✅ 静态资源 CDN +- ✅ API 响应缓存 + +### 3. 开发规范 +- ✅ 遵循 RESTful API 设计 +- ✅ 使用 TypeScript (可选) +- ✅ 编写单元测试 +- ✅ 代码审查 +- ✅ Git 提交规范 + +## 常见问题 + +### Q: 如何切换数据库? + +**从 SQLite 到 PostgreSQL:** +```python +# 修改 DATABASE_URL +DATABASE_URL = "postgresql://user:password@localhost:5432/dbname" + +# 重新创建表 +python main.py +``` + +### Q: 如何添加新的 AI 模型? + +编辑 `backend/.env`: +```bash +AI_MODEL=google/gemini-3-pro-preview +# 或 +AI_MODEL=openai/gpt-4o +``` + +### Q: 前端如何跨域请求? + +开发环境在 `vite.config.js` 配置代理: +```javascript +export default defineConfig({ + server: { + proxy: { + '/api': { + target: 'http://localhost:8888', + changeOrigin: true + } + } + } +}) +``` + +### Q: 如何部署到云服务器? + +1. 购买云服务器 (阿里云/腾讯云/AWS) +2. 配置安全组开放端口 +3. 使用 Docker 或 PM2 部署 +4. 配置域名和 HTTPS + +## 模板更新 + +如果模板有更新,你可以: + +1. **选择性合并**: +```bash +git remote add template /path/to/template +git fetch template +git cherry-pick +``` + +2. **手动更新**: +比较新旧文件,手动复制需要的功能 + +## 技术支持 + +- 查看 `CLAUDE.md` 了解详细项目文档 +- 查看 `README.md` 了解部署指南 +- FastAPI 文档: https://fastapi.tiangolo.com +- Vue 3 文档: https://vuejs.org +- Element Plus 文档: https://element-plus.org + +## 许可证 + +MIT License - 自由使用和修改 + +--- + +**祝你的项目开发顺利!** 🚀 diff --git a/TEMPLATE_QUICK_START.md b/TEMPLATE_QUICK_START.md new file mode 100644 index 0000000..a0950b6 --- /dev/null +++ b/TEMPLATE_QUICK_START.md @@ -0,0 +1,288 @@ +# 模板快速使用指南 + +## 三种使用方式 + +### 🚀 方式一: 自动化脚本 (最推荐) + +```bash +# 1. 运行创建脚本 +./create-from-template.sh + +# 2. 按提示输入项目信息 +# 3. 脚本会自动完成所有配置 +# 4. 进入新项目目录开始开发 +``` + +**优点**: +- ✅ 一键创建,无需手动配置 +- ✅ 自动替换所有配置项 +- ✅ 自动生成安全的 SECRET_KEY +- ✅ 自动初始化 Git 仓库 + +--- + +### 📋 方式二: 手动复制 + +```bash +# 1. 复制项目 +cp -r /path/to/pager /path/to/your-new-project +cd /path/to/your-new-project + +# 2. 清理不需要的文件 +rm -rf .git backend/__pycache__ backend/*.db backend/uploads/* frontend/node_modules frontend/dist + +# 3. 配置后端 +cd backend +cp .env.example .env +# 编辑 .env 文件,修改必要配置 + +# 4. 配置前端 +cd frontend +# 编辑 package.json,修改项目名称 + +# 5. 初始化 Git +git init +git add . +git commit -m "Initial commit" +``` + +--- + +### 🔗 方式三: Git 模板方式 + +```bash +# 1. 克隆为模板 +git clone /path/to/pager your-new-project +cd your-new-project + +# 2. 移除原有 Git 历史 +rm -rf .git + +# 3. 按方式二的步骤 3-5 操作 +``` + +--- + +## 核心配置清单 + +### ✅ 必须修改的配置 + +**后端 `backend/.env`:** +```bash +# 1. 数据库连接 (必须) +DATABASE_URL=postgresql://user:pass@host:port/dbname + +# 2. 密钥 (必须,生产环境) +SECRET_KEY=<生成一个长随机字符串> + +# 3. AI API Key (如需 AI 功能) +OPENROUTER_API_KEY= +``` + +**前端 `frontend/package.json`:** +```json +{ + "name": "your-project-name-frontend" +} +``` + +**前端 `frontend/index.html`:** +```html +Your Project Name +``` + +--- + +### 🔧 可选修改的配置 + +**端口配置:** +- 后端: `backend/main.py` 或 `.env` 中的 `PORT` +- 前端: `vite.config.js` 中的 `server.port` + +**API 地址:** +- `frontend/src/config/index.js` + +--- + +## 快速命令参考 + +### 开发环境 + +```bash +# 后端 +cd backend +pip install -r requirements.txt # 安装依赖 +python main.py # 启动服务 + +# 前端 +cd frontend +npm install # 安装依赖 +npm run dev # 启动开发服务器 + +# 或使用启动脚本 +./start.sh # 同时启动前后端 +./status.sh # 查看运行状态 +./stop.sh # 停止所有服务 +``` + +### 数据库操作 + +```bash +cd backend +python main.py # 首次运行自动创建表 +python migrate_db.py # 手动迁移数据库 +``` + +### 生产构建 + +```bash +# 前端构建 +cd frontend +npm run build # 构建到 dist/ 目录 +npm run preview # 预览生产构建 + +# 后端生产运行 +cd backend +uvicorn main:app --host 0.0.0.0 --port 8888 +``` + +--- + +## 项目结构速览 + +``` +your-project/ +├── backend/ # FastAPI 后端 +│ ├── main.py # 主应用 (所有 API 在这里) +│ ├── .env # 环境变量 (从 .env.example 复制) +│ └── requirements.txt # Python 依赖 +│ +├── frontend/ # Vue 3 前端 +│ ├── src/ +│ │ ├── views/ # 页面组件 +│ │ ├── stores/ # Pinia 状态管理 +│ │ ├── router/ # 路由配置 +│ │ └── config/ # 配置管理 +│ └── package.json # 前端依赖 +│ +├── create-from-template.sh # 模板创建脚本 +├── TEMPLATE_GUIDE.md # 完整使用指南 +└── start.sh # 开发启动脚本 +``` + +--- + +## 开发工作流 + +### 添加新功能 + +**1. 后端 API:** +```python +# backend/main.py +@app.get("/api/your-endpoint") +async def your_endpoint(current_user: User = Depends(get_current_user)): + return {"message": "Hello"} +``` + +**2. 前端页面:** +```bash +# 创建组件 +touch frontend/src/views/YourPage.vue + +# 注册路由 (frontend/src/router/index.js) +{ + path: '/your-page', + component: () => import('../views/YourPage.vue') +} +``` + +**3. 状态管理:** +```javascript +// frontend/src/stores/yourStore.js +import { defineStore } from 'pinia' + +export const useYourStore = defineStore('your-store', () => { + // 定义状态和方法 +}) +``` + +--- + +## 常见问题速查 + +| 问题 | 解决方法 | +|------|---------| +| 端口被占用 | 修改 `.env` 中的 `PORT` 或 `vite.config.js` | +| CORS 错误 | 检查 `backend/main.py` 的 CORS 配置 | +| 数据库连接失败 | 检查 `DATABASE_URL` 格式和数据库服务状态 | +| 前端请求失败 | 检查 `frontend/src/config/index.js` 的 API_BASE_URL | +| JWT 认证失败 | 确保 `SECRET_KEY` 正确且前后端一致 | + +--- + +## 安全检查清单 + +- [ ] 修改了 `SECRET_KEY` (生产环境必须) +- [ ] 不提交 `.env` 文件到 Git +- [ ] 生产环境设置 `DEBUG=false` +- [ ] 限制 CORS 允许的域名 +- [ ] 使用 HTTPS (生产环境) +- [ ] 定期更新依赖包 +- [ ] 保护 API keys 安全 + +--- + +## 生成安全密钥 + +```bash +# 方法 1: OpenSSL +openssl rand -base64 32 + +# 方法 2: Python +python -c "import secrets; print(secrets.token_urlsafe(32))" + +# 方法 3: Node.js +node -e "console.log(require('crypto').randomBytes(32).toString('base64'))" +``` + +--- + +## 部署选项 + +### Docker +```bash +docker-compose up -d +``` + +### PM2 +```bash +pm2 start backend/main.py --name api +pm2 serve frontend/dist 3000 --name frontend +``` + +### 云服务器 +- 阿里云 ECS +- 腾讯云 CVM +- AWS EC2 +- DigitalOcean Droplet + +--- + +## 获取帮助 + +- 📖 完整文档: `TEMPLATE_GUIDE.md` +- 🏗️ 项目架构: `CLAUDE.md` +- 📋 部署指南: `README.md` +- ⚙️ 配置说明: `backend/.env.example` + +--- + +## 下一步 + +1. ✅ 使用 `create-from-template.sh` 创建新项目 +2. ✅ 配置 `backend/.env` +3. ✅ 安装依赖 (后端+前端) +4. ✅ 启动开发服务器 +5. ✅ 开始开发你的功能 + +**祝你的项目开发顺利!** 🎉 diff --git a/backend/.env.example b/backend/.env.example index a2dd1e3..7d08ec9 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -1,23 +1,182 @@ +# ============================================================================= # Database Configuration +# ============================================================================= +# +# For SQLite (recommended for development): +# DATABASE_URL=sqlite:///./database_name.db +# +# For PostgreSQL (recommended for production): +# DATABASE_URL=postgresql://username:password@host:port/database_name +# +# For MySQL: +# DATABASE_URL=mysql://username:password@host:port/database_name +# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/wordmaster -# JWT Configuration -SECRET_KEY=your-super-secret-and-secure-key-change-me +# ============================================================================= +# Security Configuration +# ============================================================================= +# +# IMPORTANT: Change SECRET_KEY in production! +# Generate a secure key with: openssl rand -base64 32 +# Or: python -c "import secrets; print(secrets.token_urlsafe(32))" +# +SECRET_KEY=your-super-secret-and-secure-key-change-me-in-production + +# JWT algorithm (HS256 is recommended) ALGORITHM=HS256 + +# Token expiration time in minutes ACCESS_TOKEN_EXPIRE_MINUTES=30 -# OpenRouter AI Configuration (for Claude Sonnet 4.5 access) +# ============================================================================= +# OpenRouter AI Configuration +# ============================================================================= +# # Get your API key from: https://openrouter.ai/keys -OPENROUTER_API_KEY=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 +# Required if you want to use AI-powered features +# +OPENROUTER_API_KEY=your-openrouter-api-key-here +# ============================================================================= # AI Model Selection -# Available models: -# - anthropic/claude-sonnet-4.5 (默认,通用能力强) -# - google/gemini-3-pro-preview (数学能力强,推荐数学试卷使用) -# - openai/gpt-4o -# - openai/gpt-4-turbo +# ============================================================================= +# +# Available models through OpenRouter: +# +# Claude Models (Anthropic): +# - anthropic/claude-sonnet-4.5 (Default, best general performance) +# - anthropic/claude-opus-4 (Most capable, slower) +# - anthropic/claude-haiku-3.5 (Fast, cost-effective) +# +# Gemini Models (Google): +# - google/gemini-3-pro-preview (Great for math, recommended for math exams) +# - google/gemini-pro-1.5 (Good general performance) +# +# GPT Models (OpenAI): +# - openai/gpt-4o (Latest GPT-4 with vision) +# - openai/gpt-4-turbo (Fast GPT-4) +# - openai/gpt-3.5-turbo (Fastest, most economical) +# AI_MODEL=anthropic/claude-sonnet-4.5 +# ============================================================================= # Parser Configuration -# Set to "true" to use Claude AI parser by default, "false" to use traditional parser +# ============================================================================= +# +# Use AI-powered parser for better accuracy (requires OPENROUTER_API_KEY) +# Set to "false" to use traditional rule-based parser +# USE_CLAUDE_PARSER=true + +# ============================================================================= +# Application Configuration +# ============================================================================= +# +# Server host and port +HOST=0.0.0.0 +PORT=8888 + +# Environment: development, staging, production +ENVIRONMENT=development + +# Enable debug mode (set to false in production) +DEBUG=true + +# ============================================================================= +# CORS Configuration +# ============================================================================= +# +# Allowed origins for CORS (comma-separated) +# Use "*" for development, specific domains for production +# +# Examples: +# CORS_ORIGINS=http://localhost:3000,http://localhost:3001 +# CORS_ORIGINS=https://yourdomain.com,https://www.yourdomain.com +# +CORS_ORIGINS=* + +# ============================================================================= +# File Upload Configuration +# ============================================================================= +# +# Maximum file size in MB +MAX_UPLOAD_SIZE=50 + +# Allowed file extensions (comma-separated) +ALLOWED_EXTENSIONS=.pdf,.jpg,.jpeg,.png,.doc,.docx + +# Upload directory (relative to backend/) +UPLOAD_DIR=uploads + +# ============================================================================= +# Logging Configuration +# ============================================================================= +# +# Log level: DEBUG, INFO, WARNING, ERROR, CRITICAL +LOG_LEVEL=INFO + +# Log file path (leave empty to disable file logging) +LOG_FILE=logs/app.log + +# ============================================================================= +# Feature Flags +# ============================================================================= +# +# Enable/disable specific features +# +ENABLE_AI_FEATURES=true +ENABLE_PDF_PROCESSING=true +ENABLE_FILE_UPLOAD=true +ENABLE_ANALYTICS=true + +# ============================================================================= +# Rate Limiting (Optional) +# ============================================================================= +# +# Requests per minute per user +RATE_LIMIT_PER_MINUTE=60 + +# ============================================================================= +# Email Configuration (Optional) +# ============================================================================= +# +# SMTP settings for sending emails +# Leave empty if not using email features +# +# SMTP_HOST=smtp.gmail.com +# SMTP_PORT=587 +# SMTP_USER=your-email@gmail.com +# SMTP_PASSWORD=your-app-password +# SMTP_FROM=noreply@yourdomain.com + +# ============================================================================= +# Redis Configuration (Optional) +# ============================================================================= +# +# For caching and session management +# Leave empty if not using Redis +# +# REDIS_URL=redis://localhost:6379/0 + +# ============================================================================= +# Sentry Configuration (Optional) +# ============================================================================= +# +# For error tracking and monitoring +# Get your DSN from: https://sentry.io +# +# SENTRY_DSN=your-sentry-dsn-here + +# ============================================================================= +# Notes +# ============================================================================= +# +# 1. Copy this file to .env and update the values +# 2. Never commit .env to version control +# 3. Use strong, unique values for SECRET_KEY in production +# 4. Set DEBUG=false in production +# 5. Use specific CORS_ORIGINS in production +# 6. Keep API keys secure and rotate them regularly +# +# ============================================================================= diff --git a/create-from-template.sh b/create-from-template.sh new file mode 100755 index 0000000..7e6b4b3 --- /dev/null +++ b/create-from-template.sh @@ -0,0 +1,513 @@ +#!/bin/bash + +# 项目模板创建脚本 +# 用法: ./create-from-template.sh [目标目录] + +set -e # 遇到错误立即退出 + +# 颜色定义 +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# 打印带颜色的消息 +print_success() { + echo -e "${GREEN}✓ $1${NC}" +} + +print_info() { + echo -e "${BLUE}ℹ $1${NC}" +} + +print_warning() { + echo -e "${YELLOW}⚠ $1${NC}" +} + +print_error() { + echo -e "${RED}✗ $1${NC}" +} + +print_header() { + echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}" + echo -e "${BLUE} $1${NC}" + echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}" +} + +# 获取当前模板目录 +TEMPLATE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +# 欢迎信息 +clear +print_header "FastAPI + Vue 3 项目模板生成器" +echo "" +print_info "此脚本将基于当前模板创建一个新项目" +echo "" + +# 获取目标目录 +if [ -n "$1" ]; then + TARGET_DIR="$1" +else + read -p "$(echo -e ${BLUE}请输入新项目目录 [默认: ../my-new-project]: ${NC})" TARGET_DIR + TARGET_DIR=${TARGET_DIR:-../my-new-project} +fi + +# 转换为绝对路径 +TARGET_DIR=$(cd "$(dirname "$TARGET_DIR")" 2>/dev/null && pwd)/$(basename "$TARGET_DIR") || TARGET_DIR="$TARGET_DIR" + +# 检查目标目录是否已存在 +if [ -d "$TARGET_DIR" ]; then + print_warning "目录 $TARGET_DIR 已存在" + read -p "$(echo -e ${YELLOW}是否覆盖? [y/N]: ${NC})" OVERWRITE + if [[ ! $OVERWRITE =~ ^[Yy]$ ]]; then + print_info "已取消" + exit 0 + fi + rm -rf "$TARGET_DIR" +fi + +echo "" +print_header "项目配置" +echo "" + +# 收集项目信息 +read -p "$(echo -e ${BLUE}项目名称 (小写,用连字符) [my-app]: ${NC})" PROJECT_NAME +PROJECT_NAME=${PROJECT_NAME:-my-app} + +read -p "$(echo -e ${BLUE}项目显示名称 [My Application]: ${NC})" PROJECT_DISPLAY_NAME +PROJECT_DISPLAY_NAME=${PROJECT_DISPLAY_NAME:-My Application} + +read -p "$(echo -e ${BLUE}数据库名称 [${PROJECT_NAME//-/_}_db]: ${NC})" DATABASE_NAME +DATABASE_NAME=${DATABASE_NAME:-${PROJECT_NAME//-/_}_db} + +read -p "$(echo -e ${BLUE}后端 API 端口 [8888]: ${NC})" API_PORT +API_PORT=${API_PORT:-8888} + +read -p "$(echo -e ${BLUE}前端开发端口 [3000]: ${NC})" FRONTEND_PORT +FRONTEND_PORT=${FRONTEND_PORT:-3000} + +read -p "$(echo -e ${BLUE}域名 (可选,按回车跳过): ${NC})" DOMAIN_NAME + +# 数据库类型 +echo "" +echo -e "${BLUE}选择数据库类型:${NC}" +echo " 1) SQLite (默认,适合开发)" +echo " 2) PostgreSQL (推荐生产环境)" +read -p "$(echo -e ${BLUE}请选择 [1]: ${NC})" DB_TYPE +DB_TYPE=${DB_TYPE:-1} + +if [ "$DB_TYPE" = "2" ]; then + read -p "$(echo -e ${BLUE}PostgreSQL 主机 [localhost]: ${NC})" PG_HOST + PG_HOST=${PG_HOST:-localhost} + + read -p "$(echo -e ${BLUE}PostgreSQL 端口 [5432]: ${NC})" PG_PORT + PG_PORT=${PG_PORT:-5432} + + read -p "$(echo -e ${BLUE}PostgreSQL 用户名 [postgres]: ${NC})" PG_USER + PG_USER=${PG_USER:-postgres} + + read -s -p "$(echo -e ${BLUE}PostgreSQL 密码: ${NC})" PG_PASSWORD + echo "" + + DATABASE_URL="postgresql://${PG_USER}:${PG_PASSWORD}@${PG_HOST}:${PG_PORT}/${DATABASE_NAME}" +else + DATABASE_URL="sqlite:///./${DATABASE_NAME}.db" +fi + +# 生成随机 SECRET_KEY +SECRET_KEY=$(openssl rand -base64 32 2>/dev/null || python3 -c "import secrets; print(secrets.token_urlsafe(32))") + +# 确认信息 +echo "" +print_header "配置确认" +echo "" +echo -e "${BLUE}项目名称:${NC} $PROJECT_NAME" +echo -e "${BLUE}显示名称:${NC} $PROJECT_DISPLAY_NAME" +echo -e "${BLUE}数据库名称:${NC} $DATABASE_NAME" +echo -e "${BLUE}数据库 URL:${NC} $DATABASE_URL" +echo -e "${BLUE}API 端口:${NC} $API_PORT" +echo -e "${BLUE}前端端口:${NC} $FRONTEND_PORT" +echo -e "${BLUE}域名:${NC} ${DOMAIN_NAME:-未设置}" +echo -e "${BLUE}目标目录:${NC} $TARGET_DIR" +echo "" + +read -p "$(echo -e ${BLUE}确认创建项目? [Y/n]: ${NC})" CONFIRM +if [[ $CONFIRM =~ ^[Nn]$ ]]; then + print_info "已取消" + exit 0 +fi + +# 开始创建项目 +echo "" +print_header "创建项目" +echo "" + +# 1. 创建目标目录 +print_info "创建目录: $TARGET_DIR" +mkdir -p "$TARGET_DIR" + +# 2. 复制文件 +print_info "复制项目文件..." +rsync -a --progress "$TEMPLATE_DIR/" "$TARGET_DIR/" \ + --exclude='.git' \ + --exclude='node_modules' \ + --exclude='__pycache__' \ + --exclude='*.pyc' \ + --exclude='dist' \ + --exclude='backend/wordmaster.db' \ + --exclude='backend/uploads/*' \ + --exclude='frontend/.env.local' \ + --exclude='.DS_Store' + +print_success "文件复制完成" + +# 3. 替换配置 +print_info "更新配置文件..." + +cd "$TARGET_DIR" + +# 替换后端配置 +if [ -f "backend/main.py" ]; then + # macOS 和 Linux 兼容的 sed + if [[ "$OSTYPE" == "darwin"* ]]; then + sed -i '' "s/wordmaster/$DATABASE_NAME/g" backend/main.py + sed -i '' "s/学习助手 Pro/$PROJECT_DISPLAY_NAME/g" backend/main.py + else + sed -i "s/wordmaster/$DATABASE_NAME/g" backend/main.py + sed -i "s/学习助手 Pro/$PROJECT_DISPLAY_NAME/g" backend/main.py + fi +fi + +# 创建 .env 文件 +cat > backend/.env << EOF +# Database Configuration +DATABASE_URL=$DATABASE_URL + +# JWT Configuration +SECRET_KEY=$SECRET_KEY +ALGORITHM=HS256 +ACCESS_TOKEN_EXPIRE_MINUTES=30 + +# OpenRouter AI Configuration (for Claude Sonnet 4.5 access) +# Get your API key from: https://openrouter.ai/keys +OPENROUTER_API_KEY=your-openrouter-api-key-here + +# AI Model Selection +# Available models: +# - anthropic/claude-sonnet-4.5 (默认,通用能力强) +# - google/gemini-3-pro-preview (数学能力强,推荐数学试卷使用) +# - openai/gpt-4o +# - openai/gpt-4-turbo +AI_MODEL=anthropic/claude-sonnet-4.5 + +# Parser Configuration +USE_CLAUDE_PARSER=true +EOF + +print_success "后端配置已更新" + +# 替换前端配置 +if [ -f "frontend/package.json" ]; then + if [[ "$OSTYPE" == "darwin"* ]]; then + sed -i '' "s/\"name\": \"wordmaster-frontend\"/\"name\": \"$PROJECT_NAME-frontend\"/g" frontend/package.json + else + sed -i "s/\"name\": \"wordmaster-frontend\"/\"name\": \"$PROJECT_NAME-frontend\"/g" frontend/package.json + fi +fi + +if [ -f "frontend/index.html" ]; then + if [[ "$OSTYPE" == "darwin"* ]]; then + sed -i '' "s/.*<\/title>/<title>$PROJECT_DISPLAY_NAME<\/title>/g" frontend/index.html + else + sed -i "s/<title>.*<\/title>/<title>$PROJECT_DISPLAY_NAME<\/title>/g" frontend/index.html + fi +fi + +# 更新前端配置文件 +if [ -f "frontend/src/config/index.js" ]; then + if [[ "$OSTYPE" == "darwin"* ]]; then + sed -i '' "s/:8888/:$API_PORT/g" frontend/src/config/index.js + else + sed -i "s/:8888/:$API_PORT/g" frontend/src/config/index.js + fi +fi + +print_success "前端配置已更新" + +# 4. 创建 README +print_info "生成项目 README..." + +cat > README.md << EOF +# $PROJECT_DISPLAY_NAME + +基于 FastAPI + Vue 3 全栈模板创建的项目。 + +## 快速启动 + +### 后端 + +\`\`\`bash +cd backend + +# 安装依赖 +pip install -r requirements.txt + +# 启动服务 +python main.py +# 访问 http://localhost:$API_PORT +# API 文档: http://localhost:$API_PORT/docs +\`\`\` + +### 前端 + +\`\`\`bash +cd frontend + +# 安装依赖 +npm install + +# 启动开发服务器 +npm run dev +# 访问 http://localhost:$FRONTEND_PORT +\`\`\` + +### 使用启动脚本 + +\`\`\`bash +# 同时启动前后端 +./start.sh + +# 查看状态 +./status.sh + +# 停止所有服务 +./stop.sh +\`\`\` + +## 配置 + +### 环境变量 + +后端配置文件: \`backend/.env\` + +主要配置项: +- \`DATABASE_URL\`: 数据库连接 +- \`SECRET_KEY\`: JWT 密钥 (已自动生成) +- \`OPENROUTER_API_KEY\`: AI API 密钥 (可选) + +### 端口配置 + +- 后端 API: $API_PORT +- 前端开发: $FRONTEND_PORT + +## 数据库 + +- 类型: $([ "$DB_TYPE" = "2" ] && echo "PostgreSQL" || echo "SQLite") +- 数据库名: $DATABASE_NAME +$([ "$DB_TYPE" = "2" ] && echo "- 连接: $PG_HOST:$PG_PORT" || echo "- 文件: $DATABASE_NAME.db") + +首次运行时会自动创建数据库表。 + +## 技术栈 + +**后端:** +- FastAPI - 高性能 Web 框架 +- SQLAlchemy - ORM +- JWT - 身份认证 +- Pydantic - 数据验证 + +**前端:** +- Vue 3 - 渐进式框架 +- Element Plus - UI 组件库 +- Pinia - 状态管理 +- Vite - 构建工具 + +## 文档 + +- 查看 \`TEMPLATE_GUIDE.md\` 了解详细开发指南 +- 查看 \`CLAUDE.md\` 了解项目架构 + +## 部署 + +请参考 \`TEMPLATE_GUIDE.md\` 中的部署章节。 + +--- + +创建时间: $(date +%Y-%m-%d) +EOF + +print_success "README 已生成" + +# 5. 初始化 git +print_info "初始化 Git 仓库..." +git init +git add . +git commit -m "Initial commit: Created from template + +Project: $PROJECT_DISPLAY_NAME +Database: $DATABASE_NAME +API Port: $API_PORT +Frontend Port: $FRONTEND_PORT +" + +print_success "Git 仓库已初始化" + +# 6. 创建启动帮助文档 +cat > GETTING_STARTED.md << EOF +# 快速开始指南 + +## 第一次运行 + +### 1. 配置环境 + +#### 后端配置 +已自动生成 \`backend/.env\` 文件,主要配置: +- ✅ 数据库已配置: $DATABASE_NAME +- ✅ JWT 密钥已生成 +- ⚠️ 如需 AI 功能,请在 \`backend/.env\` 中设置 \`OPENROUTER_API_KEY\` + +#### 前端配置 +默认配置已就绪,无需修改。 + +### 2. 安装依赖 + +#### 后端依赖 +\`\`\`bash +cd backend +pip install -r requirements.txt +\`\`\` + +推荐使用虚拟环境: +\`\`\`bash +python -m venv venv +source venv/bin/activate # Linux/Mac +# 或 +venv\\Scripts\\activate # Windows +pip install -r requirements.txt +\`\`\` + +#### 前端依赖 +\`\`\`bash +cd frontend +npm install +# 或使用 yarn +yarn install +\`\`\` + +### 3. 启动开发服务器 + +#### 方式一: 使用启动脚本 (推荐) +\`\`\`bash +./start.sh +\`\`\` + +#### 方式二: 手动启动 + +**后端:** +\`\`\`bash +cd backend +python main.py +\`\`\` + +**前端:** +\`\`\`bash +cd frontend +npm run dev +\`\`\` + +### 4. 访问应用 + +- 前端界面: http://localhost:$FRONTEND_PORT +- 后端 API: http://localhost:$API_PORT +- API 文档: http://localhost:$API_PORT/docs + +### 5. 默认账户 + +首次访问需要注册账户。系统会自动创建数据库表。 + +## 开发流程 + +### 添加新功能 + +1. **后端 API** + - 编辑 \`backend/main.py\` + - 添加新的端点和数据模型 + - 自动重载会生效 + +2. **前端页面** + - 在 \`frontend/src/views/\` 创建新组件 + - 在 \`frontend/src/router/index.js\` 注册路由 + - Vite 会自动热更新 + +3. **状态管理** + - 在 \`frontend/src/stores/\` 创建新 store + - 使用 Pinia 管理全局状态 + +### 调试技巧 + +**后端调试:** +- 查看终端日志 +- 访问 http://localhost:$API_PORT/docs 测试 API +- 使用 Python 调试器 + +**前端调试:** +- 使用浏览器开发者工具 +- Vue DevTools 扩展 +- 检查网络请求 + +## 常见问题 + +### 端口被占用 +修改配置文件中的端口号: +- 后端: \`backend/.env\` 或 \`backend/main.py\` +- 前端: \`frontend/vite.config.js\` + +### 数据库连接失败 +- SQLite: 检查文件权限 +- PostgreSQL: 检查连接字符串和服务状态 + +### 前端 API 请求失败 +检查 \`frontend/src/config/index.js\` 中的 API_BASE_URL 配置 + +## 下一步 + +- 📖 阅读 \`TEMPLATE_GUIDE.md\` 了解完整功能 +- 🔧 根据需求定制功能模块 +- 🚀 参考部署指南发布应用 + +祝开发顺利! 🎉 +EOF + +print_success "快速开始指南已生成" + +# 完成 +echo "" +print_header "项目创建完成!" +echo "" +echo -e "${GREEN}✨ 项目已成功创建在: $TARGET_DIR${NC}" +echo "" +echo -e "${BLUE}下一步:${NC}" +echo "" +echo -e " 1. 进入项目目录:" +echo -e " ${YELLOW}cd $TARGET_DIR${NC}" +echo "" +echo -e " 2. 安装后端依赖:" +echo -e " ${YELLOW}cd backend && pip install -r requirements.txt${NC}" +echo "" +echo -e " 3. 安装前端依赖:" +echo -e " ${YELLOW}cd frontend && npm install${NC}" +echo "" +echo -e " 4. 启动项目:" +echo -e " ${YELLOW}./start.sh${NC}" +echo "" +echo -e " 5. 访问应用:" +echo -e " ${YELLOW}http://localhost:$FRONTEND_PORT${NC}" +echo "" +echo -e "${BLUE}📚 详细文档:${NC}" +echo -e " - GETTING_STARTED.md - 快速开始" +echo -e " - TEMPLATE_GUIDE.md - 完整指南" +echo -e " - README.md - 项目说明" +echo "" +print_success "祝您开发顺利! 🚀" +echo "" diff --git a/template.config.json b/template.config.json new file mode 100644 index 0000000..bd869e7 --- /dev/null +++ b/template.config.json @@ -0,0 +1,114 @@ +{ + "template": { + "name": "FastAPI-Vue3 Full-Stack Template", + "version": "1.0.0", + "description": "A production-ready full-stack template with FastAPI backend and Vue 3 frontend", + "author": "Your Name", + "license": "MIT" + }, + + "features": { + "backend": { + "framework": "FastAPI", + "database": "PostgreSQL/SQLite", + "authentication": "JWT", + "fileUpload": true, + "aiIntegration": true, + "pdfProcessing": true + }, + "frontend": { + "framework": "Vue 3", + "uiLibrary": "Element Plus", + "stateManagement": "Pinia", + "buildTool": "Vite", + "router": true + } + }, + + "configurable": { + "projectName": { + "description": "Your new project name", + "default": "my-app", + "placeholder": "my-awesome-app" + }, + "projectDisplayName": { + "description": "Display name for your application", + "default": "My Application", + "placeholder": "My Awesome App" + }, + "databaseName": { + "description": "Database name", + "default": "myapp_db", + "placeholder": "your_database_name" + }, + "apiPort": { + "description": "Backend API port", + "default": 8888, + "placeholder": 8888 + }, + "frontendPort": { + "description": "Frontend development server port", + "default": 3000, + "placeholder": 3000 + }, + "domainName": { + "description": "Production domain (optional)", + "default": "", + "placeholder": "your-domain.com" + } + }, + + "replacements": { + "backend": [ + { + "file": "backend/main.py", + "patterns": [ + {"find": "wordmaster", "replace": "{{databaseName}}"}, + {"find": "学习助手 Pro", "replace": "{{projectDisplayName}}"} + ] + }, + { + "file": "backend/.env.example", + "patterns": [ + {"find": "wordmaster", "replace": "{{databaseName}}"}, + {"find": "8888", "replace": "{{apiPort}}"} + ] + } + ], + "frontend": [ + { + "file": "frontend/package.json", + "patterns": [ + {"find": "wordmaster-frontend", "replace": "{{projectName}}-frontend"} + ] + }, + { + "file": "frontend/src/config/index.js", + "patterns": [ + {"find": "8888", "replace": "{{apiPort}}"} + ] + }, + { + "file": "frontend/index.html", + "patterns": [ + {"find": "学习助手 Pro", "replace": "{{projectDisplayName}}"} + ] + } + ] + }, + + "cleanupFiles": [ + "backend/wordmaster.db", + "backend/uploads/*", + "backend/__pycache__", + "frontend/node_modules", + "frontend/dist", + ".git" + ], + + "keepExampleFiles": [ + "backend/.env.example", + "TEMPLATE_GUIDE.md", + "template.config.json" + ] +}