Files
full-stack-doc/backend/fix_module_import.py
2025-10-14 20:05:29 +08:00

264 lines
7.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
# 修复模块导入问题的脚本
import os
import sys
from pathlib import Path
def check_project_structure():
"""检查项目结构"""
print("=== 检查项目结构 ===")
current_dir = Path.cwd()
print(f"当前目录: {current_dir}")
# 检查app目录
app_dir = current_dir / 'app'
if app_dir.exists():
print("✓ app目录存在")
else:
print("✗ app目录不存在")
return False
# 检查app/core目录
core_dir = app_dir / 'core'
if core_dir.exists():
print("✓ app/core目录存在")
else:
print("✗ app/core目录不存在")
return False
# 检查关键文件
key_files = [
'app/__init__.py',
'app/core/__init__.py',
'app/core/config.py',
'main.py'
]
for file_path in key_files:
if (current_dir / file_path).exists():
print(f"{file_path} 存在")
else:
print(f"{file_path} 不存在")
return False
return True
def create_missing_files():
"""创建缺失的文件"""
print("\n=== 创建缺失文件 ===")
current_dir = Path.cwd()
# 创建app/__init__.py
app_init = current_dir / 'app' / '__init__.py'
if not app_init.exists():
with open(app_init, 'w') as f:
f.write('"""云盘应用包"""\n')
print("✓ 创建 app/__init__.py")
# 创建app/core/__init__.py
core_init = current_dir / 'app' / 'core' / '__init__.py'
if not core_init.exists():
with open(core_init, 'w') as f:
f.write('"""核心模块包"""\n')
print("✓ 创建 app/core/__init__.py")
# 创建app/core/config.py如果不存在
config_file = current_dir / 'app' / 'core' / 'config.py'
if not config_file.exists():
config_content = '''from pydantic_settings import BaseSettings
from typing import List
import os
class Settings(BaseSettings):
# 基础配置
ENVIRONMENT: str = "development"
DEBUG: bool = True
# 数据库配置
DATABASE_URL: str = "mysql+pymysql://mytest_db:mytest_db@101.126.85.76:3306/mytest_db"
# Redis配置
REDIS_URL: str = "redis://localhost:6379"
# JWT配置
JWT_SECRET_KEY: str = "your-super-secret-jwt-key-change-in-production"
JWT_ALGORITHM: str = "HS256"
JWT_EXPIRE_MINUTES: int = 30
JWT_REFRESH_EXPIRE_DAYS: int = 7
# CORS配置
ALLOWED_HOSTS: List[str] = [
"http://localhost:3000",
"http://localhost:3001",
"http://localhost:3002",
"http://localhost:3003",
"http://localhost:3004",
"http://127.0.0.1:3000",
"http://127.0.0.1:3001",
"http://127.0.0.1:3002",
"http://127.0.0.1:3003",
"http://127.0.0.1:3004",
"http://172.16.16.89:3000",
"http://172.16.16.89:3001",
"http://172.16.16.89:3002",
"http://172.16.16.89:3003",
"http://172.16.16.89:3004",
"*"
]
# 文件上传配置
MAX_FILE_SIZE: int = 10 * 1024 * 1024 # 10MB
UPLOAD_DIR: str = "uploads"
ALLOWED_EXTENSIONS: List[str] = [
# 图片
".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp", ".svg",
# 文档
".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx",
".txt", ".rtf", ".csv",
# 压缩文件
".zip", ".rar", ".7z", ".tar", ".gz",
# 音频
".mp3", ".wav", ".flac", ".aac", ".ogg",
# 视频
".mp4", ".avi", ".mkv", ".mov", ".wmv", ".flv",
# 代码文件
".py", ".js", ".html", ".css", ".json", ".xml", ".yaml", ".yml",
".java", ".cpp", ".c", ".h", ".cs", ".php", ".rb", ".go",
".sql", ".sh", ".bat", ".ps1", ".md", ".log"
]
# 安全配置
BCRYPT_ROUNDS: int = 12
class Config:
env_file = ".env"
case_sensitive = True
settings = Settings()
'''
with open(config_file, 'w') as f:
f.write(config_content)
print("✓ 创建 app/core/config.py")
def create_fixed_main_py():
"""创建修复版main.py"""
current_dir = Path.cwd()
main_file = current_dir / 'main.py'
fixed_content = '''#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
云盘后端应用主入口
"""
import os
import sys
from pathlib import Path
# 确保项目根目录在Python路径中
current_dir = Path(__file__).parent
if str(current_dir) not in sys.path:
sys.path.insert(0, str(current_dir))
try:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.core.config import settings
from app.api.v1.endpoints import health, auth, files
import uvicorn
from datetime import datetime
# 简单的日志打印函数
def log_info(message):
"""打印INFO级别日志"""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"[{timestamp}] INFO: {message}")
def log_error(message):
"""打印ERROR级别日志"""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"[{timestamp}] ERROR: {message}")
def log_debug(message):
"""打印DEBUG级别日志"""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"[{timestamp}] DEBUG: {message}")
# 确保logs目录存在
logs_dir = current_dir / "logs"
logs_dir.mkdir(exist_ok=True)
log_info("=== Server Starting ===")
log_info(f"Python version: {sys.version}")
log_info(f"Working directory: {os.getcwd()}")
log_info("Simple print logger configured")
app = FastAPI(
title="云盘应用 API",
description="现代化的云存储Web应用后端API",
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc"
)
# CORS中间件
app.add_middleware(
CORSMiddleware,
allow_origins=settings.ALLOWED_HOSTS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 包含路由
app.include_router(health.router, prefix="/api/v1", tags=["health"])
app.include_router(auth.router, prefix="/api/v1/auth", tags=["authentication"])
app.include_router(files.router, prefix="/api/v1/files", tags=["files"])
@app.get("/")
async def root():
return {"message": "云盘应用 API", "version": "1.0.1"}
if __name__ == "__main__":
uvicorn.run(
"main:app",
host="0.0.0.0",
port=8000,
reload=True if settings.ENVIRONMENT == "development" else False
)
except ImportError as e:
print(f"导入错误: {e}")
print("请确保已安装所有依赖: pip install -r requirements.txt")
print("或尝试安装基础依赖: pip install fastapi uvicorn sqlalchemy pymysql redis python-jose passlib python-multipart pydantic pydantic-settings httpx python-dotenv")
sys.exit(1)
except Exception as e:
print(f"启动错误: {e}")
sys.exit(1)
'''
with open(main_file, 'w') as f:
f.write(fixed_content)
print("✓ 创建修复版 main.py")
def main():
"""主函数"""
print("=== 修复模块导入问题 ===")
# 检查项目结构
if not check_project_structure():
print("\\n项目结构有问题开始修复...")
create_missing_files()
create_fixed_main_py()
print("\\n=== 修复完成 ===")
print("现在可以运行:")
print("1. 激活虚拟环境: source venv/bin/activate")
print("2. 安装依赖: pip install -r requirements.txt")
print("3. 启动服务: python main.py")
if __name__ == '__main__':
main()