first commit

This commit is contained in:
2026-02-14 00:46:04 +08:00
commit 7ce1e58a6e
18 changed files with 2014 additions and 0 deletions

23
backend/__init__.py Normal file
View File

@@ -0,0 +1,23 @@
# -*- coding: utf-8 -*-
"""
后端模块包
"""
from backend.golang import init_golang_project, init_gin_project
from backend.python_flask import init_flask_project
from backend.python_fastapi import init_fastapi_project
from backend.python_django import init_django_project
from backend.java_spring import init_spring_project
from backend.js_express import init_express_project
from backend.js_nestjs import init_nestjs_project
__all__ = [
'init_golang_project',
'init_gin_project',
'init_flask_project',
'init_fastapi_project',
'init_django_project',
'init_spring_project',
'init_express_project',
'init_nestjs_project'
]

202
backend/golang.py Normal file
View File

@@ -0,0 +1,202 @@
# -*- coding: utf-8 -*-
"""
Go 后端项目初始化模块
"""
import subprocess
import sys
def run_command_with_progress(cmd, cwd, description):
"""运行命令并显示实时输出"""
try:
print(f"\n{'=' * 60}")
print(f"执行: {description}")
print(f"{'=' * 60}")
process = subprocess.Popen(
cmd,
cwd=cwd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=0
)
for line in process.stdout:
try:
decoded_line = line.decode('utf-8', errors='replace')
except:
try:
decoded_line = line.decode('gbk', errors='replace')
except:
decoded_line = line.decode('latin-1', errors='replace')
print(decoded_line, end='')
process.wait()
if process.returncode == 0:
print(f"\n{'=' * 60}")
print(f"{description} - 完成")
print(f"{'=' * 60}\n")
return True
else:
print(f"\n{'=' * 60}")
print(f"{description} - 失败 (错误码: {process.returncode})")
print(f"{'=' * 60}\n")
return False
except Exception as e:
print(f"\n❌ 执行失败: {str(e)}")
return False
def init_golang_project(backend_dir, project_name):
"""初始化 Go 后端项目"""
print("\n🚀 初始化 Go 后端项目...")
# 初始化 Go 模块
success = run_command_with_progress(
f"go mod init {project_name}-backend",
backend_dir,
"初始化 Go 模块"
)
if not success:
print("\n💡 提示: 请确保已安装 Go")
print(" 下载地址: https://golang.org/dl/")
sys.exit(1)
# 创建 main.go - 使用标准库
main_go = backend_dir / "main.go"
main_go.write_text(f'''package main
import (
"encoding/json"
"log"
"net/http"
)
func main() {{
mux := http.NewServeMux()
// 健康检查接口
mux.HandleFunc("GET /api/health", healthHandler)
// 添加 CORS 中间件
handler := corsMiddleware(mux)
log.Println("🚀 服务器启动: http://localhost:8080")
log.Println("📍 健康检查: http://localhost:8080/api/health")
log.Fatal(http.ListenAndServe(":8080", handler))
}}
func healthHandler(w http.ResponseWriter, r *http.Request) {{
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{{
"status": "ok",
"message": "Welcome to {project_name} API",
}})
}}
func corsMiddleware(next http.Handler) http.Handler {{
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {{
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
if r.Method == "OPTIONS" {{
w.WriteHeader(http.StatusNoContent)
return
}}
next.ServeHTTP(w, r)
}})
}}
''', encoding='utf-8')
# 整理依赖
run_command_with_progress("go mod tidy", backend_dir, "整理 Go 依赖")
print("\n✅ Go 后端项目初始化成功")
print("💡 启动命令: go run main.go")
print("📝 注意: 使用 Go 标准库,无需第三方依赖")
def init_gin_project(backend_dir, project_name):
"""初始化 Go Gin 后端项目"""
print("\n🚀 初始化 Go Gin 后端项目...")
# 初始化 Go 模块
success = run_command_with_progress(
f"go mod init {project_name}-backend",
backend_dir,
"初始化 Go 模块"
)
if not success:
print("\n💡 提示: 请确保已安装 Go")
print(" 下载地址: https://golang.org/dl/")
sys.exit(1)
# 拉取 Gin 依赖
deps_ok = run_command_with_progress(
"go get github.com/gin-gonic/gin github.com/gin-contrib/cors",
backend_dir,
"安装 Gin 依赖"
)
if not deps_ok:
print("\n❌ 无法安装 Gin 依赖,请检查 Go 环境和网络")
sys.exit(1)
# 创建 main.go - Gin 框架
main_go = backend_dir / "main.go"
main_go.write_text(f'''package main
import (
"log"
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func main() {{
r := gin.New()
r.Use(gin.Logger())
r.Use(gin.Recovery())
// CORS 配置
r.Use(cors.New(cors.Config{{
AllowOrigins: []string{{"*"}},
AllowMethods: []string{{"GET", "POST", "PUT", "DELETE", "OPTIONS"}},
AllowHeaders: []string{{"Origin", "Content-Type", "Authorization"}},
ExposeHeaders: []string{{"Content-Length"}},
AllowCredentials: false,
MaxAge: 12 * time.Hour,
}}))
// 健康检查
r.GET("/api/health", func(c *gin.Context) {{
c.JSON(200, gin.H{{
"status": "ok",
"message": "Welcome to {project_name} API",
}})
}})
addr := ":8080"
log.Printf("🚀 Gin 服务启动: http://localhost%s", addr)
log.Printf("📍 健康检查: http://localhost%s/api/health", addr)
if err := r.Run(addr); err != nil {{
log.Fatalf("启动失败: %v", err)
}}
}}
''', encoding='utf-8')
# 整理依赖
run_command_with_progress("go mod tidy", backend_dir, "整理 Go 依赖")
print("\n✅ Go Gin 后端项目初始化成功")
print("💡 启动命令: go run main.go")

104
backend/java_spring.py Normal file
View File

@@ -0,0 +1,104 @@
# -*- coding: utf-8 -*-
"""
Java Spring Boot 后端项目初始化模块
"""
def init_spring_project(backend_dir, project_name):
"""初始化 Spring Boot 项目"""
print("\n🚀 初始化 Spring Boot 项目...")
# 创建基本的 Spring Boot 项目结构
src_main = backend_dir / "src" / "main"
src_main_java = src_main / "java" / "com" / project_name.replace("-", "")
src_main_resources = src_main / "resources"
src_main_java.mkdir(parents=True, exist_ok=True)
src_main_resources.mkdir(parents=True, exist_ok=True)
# 创建主应用类
package_name = project_name.replace("-", "")
app_java = src_main_java / "Application.java"
app_java.write_text(f'''package com.{package_name};
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.CrossOrigin;
import java.util.HashMap;
import java.util.Map;
@SpringBootApplication
@RestController
@CrossOrigin(origins = "*")
public class Application {{
public static void main(String[] args) {{
System.out.println("🚀 服务器启动: http://localhost:8080");
System.out.println("📍 健康检查: http://localhost:8080/api/health");
SpringApplication.run(Application.class, args);
}}
@GetMapping("/api/health")
public Map<String, String> health() {{
Map<String, String> response = new HashMap<>();
response.put("status", "ok");
response.put("message", "Welcome to {project_name} API");
return response;
}}
}}
''', encoding='utf-8')
# 创建 application.properties
app_properties = src_main_resources / "application.properties"
app_properties.write_text(f'''server.port=8080
spring.application.name={project_name}
''', encoding='utf-8')
# 创建 pom.xml
pom_xml = backend_dir / "pom.xml"
pom_xml.write_text(f'''<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
<relativePath/>
</parent>
<groupId>com.{package_name}</groupId>
<artifactId>{project_name}-backend</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>{project_name}</name>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
''', encoding='utf-8')
print("\n✅ Spring Boot 项目初始化成功")
print("💡 启动命令: mvn spring-boot:run")
print("⚠️ 注意: 需要安装 Maven 和 JDK 17+ 才能运行此项目")

128
backend/js_express.py Normal file
View File

@@ -0,0 +1,128 @@
# -*- coding: utf-8 -*-
"""
JavaScript Express.js 后端项目初始化模块
"""
import subprocess
import sys
def run_command_with_progress(cmd, cwd, description):
"""运行命令并显示实时输出"""
try:
print(f"\n{'=' * 60}")
print(f"执行: {description}")
print(f"{'=' * 60}")
process = subprocess.Popen(
cmd,
cwd=cwd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=0
)
for line in process.stdout:
try:
decoded_line = line.decode('utf-8', errors='replace')
except:
try:
decoded_line = line.decode('gbk', errors='replace')
except:
decoded_line = line.decode('latin-1', errors='replace')
print(decoded_line, end='')
process.wait()
if process.returncode == 0:
print(f"\n{'=' * 60}")
print(f"{description} - 完成")
print(f"{'=' * 60}\n")
return True
else:
print(f"\n{'=' * 60}")
print(f"{description} - 失败 (错误码: {process.returncode})")
print(f"{'=' * 60}\n")
return False
except Exception as e:
print(f"\n❌ 执行失败: {str(e)}")
return False
def init_express_project(backend_dir, project_name):
"""初始化 Express.js 项目"""
print("\n🚀 初始化 Express.js 项目...")
# 初始化 npm 项目
success = run_command_with_progress(
"npm init -y",
backend_dir,
"初始化 npm 项目"
)
if not success:
print("\n💡 提示: 请确保已安装 Node.js 和 npm")
print(" 下载地址: https://nodejs.org/")
sys.exit(1)
# 安装依赖
run_command_with_progress(
"npm install express cors",
backend_dir,
"安装 Express.js 依赖"
)
# 安装开发依赖
run_command_with_progress(
"npm install -D nodemon",
backend_dir,
"安装开发依赖 (nodemon)"
)
# 创建 app.js
app_js = backend_dir / "app.js"
app_js.write_text(f'''const express = require('express');
const cors = require('cors');
const app = express();
const PORT = 8080;
// 中间件
app.use(cors());
app.use(express.json());
// 健康检查接口
app.get('/api/health', (req, res) => {{
res.json({{
status: 'ok',
message: 'Welcome to {project_name} API'
}});
}});
// 示例接口
app.get('/api/hello', (req, res) => {{
res.json({{ message: 'Hello from Express.js!' }});
}});
// 启动服务器
app.listen(PORT, () => {{
console.log('🚀 服务器启动: http://localhost:' + PORT);
console.log('📍 健康检查: http://localhost:' + PORT + '/api/health');
}});
''', encoding='utf-8')
# 更新 package.json 添加脚本
package_json = backend_dir / "package.json"
import json
pkg = json.loads(package_json.read_text(encoding='utf-8'))
pkg['scripts'] = {
'start': 'node app.js',
'dev': 'nodemon app.js'
}
pkg['name'] = f'{project_name}-backend'
package_json.write_text(json.dumps(pkg, indent=2, ensure_ascii=False), encoding='utf-8')
print("\n✅ Express.js 项目初始化成功")
print("💡 启动命令: npm run dev (开发模式) 或 npm start (生产模式)")

158
backend/js_nestjs.py Normal file
View File

@@ -0,0 +1,158 @@
# -*- coding: utf-8 -*-
"""
JavaScript NestJS 后端项目初始化模块
"""
import subprocess
import sys
import shutil
def run_command_interactive(cmd, cwd, description):
"""运行命令并支持用户交互"""
print(f"\n{'=' * 60}")
print(f"执行: {description}")
print(f"{'=' * 60}")
print(f"💡 提示: 此步骤可能需要您进行交互操作")
print(f"{'=' * 60}\n")
try:
result = subprocess.run(cmd, cwd=cwd, shell=True)
print(f"\n{'=' * 60}")
if result.returncode == 0:
print(f"{description} - 完成")
else:
print(f"{description} - 失败 (错误码: {result.returncode})")
print(f"{'=' * 60}\n")
return result.returncode == 0
except Exception as e:
print(f"\n❌ 执行失败: {str(e)}")
return False
def run_command_with_progress(cmd, cwd, description):
"""运行命令并显示实时输出"""
try:
print(f"\n{'=' * 60}")
print(f"执行: {description}")
print(f"{'=' * 60}")
process = subprocess.Popen(
cmd,
cwd=cwd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=0
)
for line in process.stdout:
try:
decoded_line = line.decode('utf-8', errors='replace')
except:
try:
decoded_line = line.decode('gbk', errors='replace')
except:
decoded_line = line.decode('latin-1', errors='replace')
print(decoded_line, end='')
process.wait()
if process.returncode == 0:
print(f"\n{'=' * 60}")
print(f"{description} - 完成")
print(f"{'=' * 60}\n")
return True
else:
print(f"\n{'=' * 60}")
print(f"{description} - 失败 (错误码: {process.returncode})")
print(f"{'=' * 60}\n")
return False
except Exception as e:
print(f"\n❌ 执行失败: {str(e)}")
return False
def init_nestjs_project(backend_dir, project_name):
"""初始化 NestJS 项目"""
print("\n🚀 初始化 NestJS 项目...")
print("\n⚠️ 重要提示:")
print(" 1. NestJS CLI 会询问使用哪个包管理器,建议选择 npm")
print(" 2. 创建过程可能需要几分钟,请耐心等待\n")
# 删除空目录,因为 NestJS CLI 需要创建目录
backend_dir.rmdir()
# 使用 NestJS CLI 创建项目
success = run_command_interactive(
f"npx @nestjs/cli new {backend_dir.name} --skip-git",
backend_dir.parent,
"创建 NestJS 项目"
)
if not success:
# 如果失败,重新创建目录
backend_dir.mkdir(exist_ok=True)
print("\n💡 提示: 请确保已安装 Node.js 和 npm")
print(" 下载地址: https://nodejs.org/")
sys.exit(1)
# 检查目录是否创建成功
if not backend_dir.exists():
print("❌ 项目目录创建失败")
sys.exit(1)
# 修改默认端口为 8080 并添加 CORS
main_ts = backend_dir / "src" / "main.ts"
if main_ts.exists():
main_ts.write_text(f'''import {{ NestFactory }} from '@nestjs/core';
import {{ AppModule }} from './app.module';
async function bootstrap() {{
const app = await NestFactory.create(AppModule);
// 启用 CORS
app.enableCors();
// 设置全局前缀
app.setGlobalPrefix('api');
await app.listen(8080);
console.log('🚀 服务器启动: http://localhost:8080');
console.log('📍 健康检查: http://localhost:8080/api/health');
}}
bootstrap();
''', encoding='utf-8')
# 修改 AppController 添加健康检查
app_controller = backend_dir / "src" / "app.controller.ts"
if app_controller.exists():
app_controller.write_text(f'''import {{ Controller, Get }} from '@nestjs/common';
import {{ AppService }} from './app.service';
@Controller()
export class AppController {{
constructor(private readonly appService: AppService) {{}}
@Get('health')
health() {{
return {{
status: 'ok',
message: 'Welcome to {project_name} API',
}};
}}
@Get('hello')
getHello(): string {{
return this.appService.getHello();
}}
}}
''', encoding='utf-8')
print("\n✅ NestJS 项目初始化成功")
print("💡 启动命令: npm run start:dev (开发模式) 或 npm run start (生产模式)")
print("📚 NestJS 文档: https://docs.nestjs.com/")

206
backend/python_django.py Normal file
View File

@@ -0,0 +1,206 @@
# -*- coding: utf-8 -*-
"""
Python Django 后端项目初始化模块
"""
import subprocess
import sys
def run_command_with_progress(cmd, cwd, description):
"""运行命令并显示实时输出"""
try:
print(f"\n{'=' * 60}")
print(f"执行: {description}")
print(f"{'=' * 60}")
process = subprocess.Popen(
cmd,
cwd=cwd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=0
)
for line in process.stdout:
try:
decoded_line = line.decode('utf-8', errors='replace')
except:
try:
decoded_line = line.decode('gbk', errors='replace')
except:
decoded_line = line.decode('latin-1', errors='replace')
print(decoded_line, end='')
process.wait()
if process.returncode == 0:
print(f"\n{'=' * 60}")
print(f"{description} - 完成")
print(f"{'=' * 60}\n")
return True
else:
print(f"\n{'=' * 60}")
print(f"{description} - 失败 (错误码: {process.returncode})")
print(f"{'=' * 60}\n")
return False
except Exception as e:
print(f"\n❌ 执行失败: {str(e)}")
return False
def init_django_project(backend_dir, project_name):
"""初始化 Django 项目"""
print("\n🚀 初始化 Django 项目...")
# 创建虚拟环境
success = run_command_with_progress(
f'"{sys.executable}" -m venv venv',
backend_dir,
"创建 Python 虚拟环境"
)
if not success:
print("\n⚠️ 虚拟环境创建失败,请检查 Python 安装")
return
venv_python = backend_dir / "venv" / "Scripts" / "python.exe"
venv_pip = backend_dir / "venv" / "Scripts" / "pip.exe"
if not venv_python.exists():
print("\n⚠️ 虚拟环境创建失败")
return
# 安装 Django 和 CORS 支持
run_command_with_progress(
f'"{venv_pip}" install django django-cors-headers',
backend_dir,
"安装 Django 依赖"
)
# 使用 django-admin 创建项目
django_admin = backend_dir / "venv" / "Scripts" / "django-admin.exe"
run_command_with_progress(
f'"{django_admin}" startproject config .',
backend_dir,
"创建 Django 项目"
)
# 创建 api 应用
run_command_with_progress(
f'"{venv_python}" manage.py startapp api',
backend_dir,
"创建 api 应用"
)
# 创建 requirements.txt
requirements = backend_dir / "requirements.txt"
requirements.write_text('''Django==5.0.0
django-cors-headers==4.3.0
''', encoding='utf-8')
# 修改 settings.py 添加 CORS 和 api 应用
settings_file = backend_dir / "config" / "settings.py"
if settings_file.exists():
settings_content = settings_file.read_text(encoding='utf-8')
# 添加 INSTALLED_APPS
settings_content = settings_content.replace(
"INSTALLED_APPS = [",
"""INSTALLED_APPS = [
'corsheaders',
'api',"""
)
# 添加 MIDDLEWARE
settings_content = settings_content.replace(
"MIDDLEWARE = [",
"""MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',"""
)
# 添加 CORS 配置
settings_content += """
# CORS 配置
CORS_ALLOW_ALL_ORIGINS = True
# 允许的请求头
CORS_ALLOW_HEADERS = [
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
]
"""
settings_file.write_text(settings_content, encoding='utf-8')
# 创建 api/views.py
api_views = backend_dir / "api" / "views.py"
api_views.write_text(f'''from django.http import JsonResponse
def health(request):
"""健康检查接口"""
return JsonResponse({{
'status': 'ok',
'message': 'Welcome to {project_name} API'
}})
def hello(request):
"""示例接口"""
return JsonResponse({{
'message': 'Hello from Django!'
}})
''', encoding='utf-8')
# 创建 api/urls.py
api_urls = backend_dir / "api" / "urls.py"
api_urls.write_text('''from django.urls import path
from . import views
urlpatterns = [
path('health', views.health, name='health'),
path('hello', views.hello, name='hello'),
]
''', encoding='utf-8')
# 修改主 urls.py
main_urls = backend_dir / "config" / "urls.py"
main_urls.write_text('''from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api.urls')),
]
''', encoding='utf-8')
# 创建启动脚本 run.py
run_py = backend_dir / "run.py"
run_py.write_text('''#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
print("🚀 服务器启动: http://localhost:8080")
print("📍 健康检查: http://localhost:8080/api/health")
print("🔧 管理后台: http://localhost:8080/admin/")
from django.core.management import execute_from_command_line
execute_from_command_line(["manage.py", "runserver", "0.0.0.0:8080"])
''', encoding='utf-8')
print("\n✅ Django 项目初始化成功")
print("💡 启动命令: venv\\Scripts\\python run.py")
print("🔧 管理后台: http://localhost:8080/admin/")
print("📝 提示: 首次运行前执行 venv\\Scripts\\python manage.py migrate")

119
backend/python_fastapi.py Normal file
View File

@@ -0,0 +1,119 @@
# -*- coding: utf-8 -*-
"""
Python FastAPI 后端项目初始化模块
"""
import subprocess
import sys
def run_command_with_progress(cmd, cwd, description):
"""运行命令并显示实时输出"""
try:
print(f"\n{'=' * 60}")
print(f"执行: {description}")
print(f"{'=' * 60}")
process = subprocess.Popen(
cmd,
cwd=cwd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=0
)
for line in process.stdout:
try:
decoded_line = line.decode('utf-8', errors='replace')
except:
try:
decoded_line = line.decode('gbk', errors='replace')
except:
decoded_line = line.decode('latin-1', errors='replace')
print(decoded_line, end='')
process.wait()
if process.returncode == 0:
print(f"\n{'=' * 60}")
print(f"{description} - 完成")
print(f"{'=' * 60}\n")
return True
else:
print(f"\n{'=' * 60}")
print(f"{description} - 失败 (错误码: {process.returncode})")
print(f"{'=' * 60}\n")
return False
except Exception as e:
print(f"\n❌ 执行失败: {str(e)}")
return False
def init_fastapi_project(backend_dir, project_name):
"""初始化 FastAPI 项目"""
print("\n🚀 初始化 FastAPI 项目...")
# 创建 main.py
main_py = backend_dir / "main.py"
main_py.write_text(f'''from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
app = FastAPI(title="{project_name} API")
# 允许跨域
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/api/health")
async def health():
return {{
"status": "ok",
"message": "Welcome to {project_name} API"
}}
if __name__ == "__main__":
print("🚀 服务器启动: http://localhost:8080")
print("📍 健康检查: http://localhost:8080/api/health")
print("📚 API文档: http://localhost:8080/docs")
uvicorn.run(app, host="0.0.0.0", port=8080)
''', encoding='utf-8')
# 创建 requirements.txt
requirements = backend_dir / "requirements.txt"
requirements.write_text('''fastapi==0.109.0
uvicorn[standard]==0.27.0
''', encoding='utf-8')
# 创建虚拟环境并安装依赖
success = run_command_with_progress(
f'"{sys.executable}" -m venv venv',
backend_dir,
"创建 Python 虚拟环境"
)
if success:
venv_python = backend_dir / "venv" / "Scripts" / "python.exe"
if venv_python.exists():
success = run_command_with_progress(
f'"{venv_python}" -m pip install -r requirements.txt',
backend_dir,
"安装 FastAPI 依赖"
)
if success:
print("\n✅ FastAPI 项目初始化成功")
print("💡 启动命令: venv\\Scripts\\python main.py")
print("📚 API文档: http://localhost:8080/docs")
else:
print("\n⚠️ FastAPI 项目创建成功,但依赖安装失败")
print(f" 请手动运行: cd {project_name}-backend && venv\\Scripts\\pip install -r requirements.txt")
else:
print("\n⚠️ 虚拟环境创建失败,请检查 Python 安装")

108
backend/python_flask.py Normal file
View File

@@ -0,0 +1,108 @@
# -*- coding: utf-8 -*-
"""
Python Flask 后端项目初始化模块
"""
import subprocess
import sys
def run_command_with_progress(cmd, cwd, description):
"""运行命令并显示实时输出"""
try:
print(f"\n{'=' * 60}")
print(f"执行: {description}")
print(f"{'=' * 60}")
process = subprocess.Popen(
cmd,
cwd=cwd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=0
)
for line in process.stdout:
try:
decoded_line = line.decode('utf-8', errors='replace')
except:
try:
decoded_line = line.decode('gbk', errors='replace')
except:
decoded_line = line.decode('latin-1', errors='replace')
print(decoded_line, end='')
process.wait()
if process.returncode == 0:
print(f"\n{'=' * 60}")
print(f"{description} - 完成")
print(f"{'=' * 60}\n")
return True
else:
print(f"\n{'=' * 60}")
print(f"{description} - 失败 (错误码: {process.returncode})")
print(f"{'=' * 60}\n")
return False
except Exception as e:
print(f"\n❌ 执行失败: {str(e)}")
return False
def init_flask_project(backend_dir, project_name):
"""初始化 Flask 项目"""
print("\n🚀 初始化 Flask 项目...")
# 创建 app.py
app_py = backend_dir / "app.py"
app_py.write_text(f'''from flask import Flask, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app) # 允许跨域
@app.route('/api/health', methods=['GET'])
def health():
return jsonify({{
'status': 'ok',
'message': 'Welcome to {project_name} API'
}})
if __name__ == '__main__':
print("🚀 服务器启动: http://localhost:8080")
print("📍 健康检查: http://localhost:8080/api/health")
app.run(debug=True, host='0.0.0.0', port=8080)
''', encoding='utf-8')
# 创建 requirements.txt
requirements = backend_dir / "requirements.txt"
requirements.write_text('''Flask==3.0.0
flask-cors==4.0.0
''', encoding='utf-8')
# 创建虚拟环境并安装依赖
success = run_command_with_progress(
f'"{sys.executable}" -m venv venv',
backend_dir,
"创建 Python 虚拟环境"
)
if success:
venv_python = backend_dir / "venv" / "Scripts" / "python.exe"
if venv_python.exists():
success = run_command_with_progress(
f'"{venv_python}" -m pip install -r requirements.txt',
backend_dir,
"安装 Flask 依赖"
)
if success:
print("\n✅ Flask 项目初始化成功")
print("💡 启动命令: venv\\Scripts\\python app.py")
else:
print("\n⚠️ Flask 项目创建成功,但依赖安装失败")
print(f" 请手动运行: cd {project_name}-backend && venv\\Scripts\\pip install -r requirements.txt")
else:
print("\n⚠️ 虚拟环境创建失败,请检查 Python 安装")