first commit
This commit is contained in:
119
backend/python_fastapi.py
Normal file
119
backend/python_fastapi.py
Normal 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 安装")
|
||||
Reference in New Issue
Block a user