#!/usr/bin/env python3 """ MySQL环境启动脚本 使用MySQL数据库进行开发测试 """ import os import sys import asyncio from pathlib import Path # 设置环境变量 - 使用公网MySQL数据库 # 密码需要URL编码: Kaopeilian2025!@# -> Kaopeilian2025%21%40%23 os.environ["DATABASE_URL"] = "mysql+aiomysql://root:Kaopeilian2025%21%40%23@120.79.247.16:3306/kaopeilian" os.environ["SECRET_KEY"] = "dev-secret-key-for-testing-only-not-for-production" os.environ["DEBUG"] = "true" os.environ["LOG_LEVEL"] = "INFO" os.environ["LOG_FORMAT"] = "console" os.environ["REDIS_URL"] = "redis://localhost:6379/0" # 添加项目根目录到Python路径 project_root = Path(__file__).parent sys.path.insert(0, str(project_root)) async def create_database(): """创建数据库(如果不存在)""" try: import aiomysql # 连接到公网MySQL服务器(不指定数据库) conn = await aiomysql.connect( host='120.79.247.16', port=3306, user='root', password='Kaopeilian2025!@#' ) cursor = await conn.cursor() # 创建数据库 await cursor.execute("CREATE DATABASE IF NOT EXISTS kaopeilian CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci") print("✅ 数据库 'kaopeilian' 创建成功") await cursor.close() conn.close() except Exception as e: print(f"⚠️ 数据库创建警告: {e}") print("请确保MySQL服务正在运行,并且用户root的密码是'root'") async def create_tables(): """创建数据库表""" try: from app.config.database import engine from app.models.base import Base async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) print("✅ 数据库表创建成功") except Exception as e: print(f"❌ 数据库表创建失败: {e}") print("请检查MySQL连接配置") async def main(): """主函数""" print("🚀 启动考培练系统后端服务 (MySQL版本)...") # 创建数据库 await create_database() # 创建数据库表 await create_tables() # 启动服务 import uvicorn from app.main import app print("📚 API文档地址: http://localhost:8000/api/v1/docs") print("🔍 健康检查: http://localhost:8000/health") print("🗄️ 数据库: MySQL (kaopeilian)") print("⏹️ 按 Ctrl+C 停止服务") uvicorn.run( app, host="0.0.0.0", port=8000, reload=True, log_level="info" ) if __name__ == "__main__": asyncio.run(main())