207 lines
5.7 KiB
Python
207 lines
5.7 KiB
Python
# -*- 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")
|