superlishunqin 11c6960353 homepage
2025-09-22 07:33:00 +08:00

158 lines
4.6 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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.

import os
import logging
from datetime import datetime
from flask import Flask
from app import create_app, db
from app.models import User, EmailVerification
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(levelname)s %(name)s %(message)s',
handlers=[
logging.FileHandler('logs/app.log'),
logging.StreamHandler()
]
)
# 创建Flask应用
app = create_app(os.environ.get('FLASK_ENV', 'development'))
# 创建CLI命令
@app.cli.command()
def init_db():
"""初始化数据库"""
try:
# 创建所有表
with app.app_context():
db.create_all()
print("✅ 数据库表创建成功")
# 创建默认数据
create_default_data()
print("✅ 默认数据创建成功")
except Exception as e:
print(f"❌ 数据库初始化失败: {str(e)}")
@app.cli.command()
def drop_db():
"""删除所有数据库表"""
try:
with app.app_context():
db.drop_all()
print("✅ 数据库表删除成功")
except Exception as e:
print(f"❌ 数据库表删除失败: {str(e)}")
@app.cli.command()
def reset_db():
"""重置数据库"""
try:
with app.app_context():
db.drop_all()
db.create_all()
create_default_data()
print("✅ 数据库重置成功")
except Exception as e:
print(f"❌ 数据库重置失败: {str(e)}")
def create_default_data():
"""创建默认数据"""
with app.app_context():
# 检查是否已有数据
if User.query.first():
print("⚠️ 数据库已有数据,跳过默认数据创建")
return
# 可以在这里创建测试用户或其他默认数据
print(" 暂无默认数据需要创建")
@app.cli.command()
def test_email():
"""测试邮件发送功能"""
try:
from utils import send_verification_email
test_email = input("请输入测试邮箱地址: ").strip()
if not test_email:
print("❌ 邮箱地址不能为空")
return
test_code = "123456"
with app.app_context():
success = send_verification_email(test_email, test_code)
if success:
print(f"✅ 测试邮件发送成功到: {test_email}")
else:
print("❌ 测试邮件发送失败")
except Exception as e:
print(f"❌ 邮件测试失败: {str(e)}")
@app.cli.command()
def clean_expired_codes():
"""清理过期的验证码"""
try:
with app.app_context():
expired_codes = EmailVerification.query.filter(
EmailVerification.expires_at < datetime.utcnow()
)
count = expired_codes.count()
expired_codes.delete()
db.session.commit()
print(f"✅ 清理了 {count} 个过期验证码")
except Exception as e:
print(f"❌ 清理过期验证码失败: {str(e)}")
@app.shell_context_processor
def make_shell_context():
"""为flask shell命令提供上下文"""
return {
'db': db,
'User': User,
'EmailVerification': EmailVerification
}
if __name__ == '__main__':
import platform
# 确保日志目录存在
os.makedirs('logs', exist_ok=True)
# 运行应用
port = int(os.environ.get('PORT', 50003))
# 强制开启Debug模式便于前端开发
debug = True
# 根据操作系统选择合适的host
if platform.system() == 'Darwin': # macOS
host = '127.0.0.1'
else:
host = os.environ.get('HOST', '0.0.0.0')
print("🚀 启动儿童语言学习系统...")
print(f"📱 访问地址: http://localhost:{port}")
print(f"🔧 调试模式: {debug}")
print(f"🌐 监听地址: {host}:{port}")
print(f"📊 数据库: {app.config['SQLALCHEMY_DATABASE_URI']}")
try:
app.run(host=host, port=port, debug=debug)
except OSError as e:
if "Unknown host" in str(e) or "getfqdn" in str(e):
print("⚠️ 检测到主机名解析问题尝试使用localhost...")
try:
app.run(host='localhost', port=port, debug=debug)
except Exception as e2:
print(f"❌ 启动失败: {e2}")
print("💡 尝试使用: python3 run.py 或检查网络配置")
else:
print(f"❌ 启动失败: {e}")
except KeyboardInterrupt:
print("服务器已停止")
except Exception as e:
print(f"❌ 启动失败: {e}")