Files
012-kaopeilian/backend/scripts/cleanup_users.py
111 998211c483 feat: 初始化考培练系统项目
- 从服务器拉取完整代码
- 按框架规范整理项目结构
- 配置 Drone CI 测试环境部署
- 包含后端(FastAPI)、前端(Vue3)、管理端

技术栈: Vue3 + TypeScript + FastAPI + MySQL
2026-01-24 19:33:28 +08:00

79 lines
2.5 KiB
Python
Raw Permalink 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
"""
用户清理脚本
删除除admin以外的所有用户为员工同步做准备
"""
import asyncio
import sys
from pathlib import Path
# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).parent.parent))
from sqlalchemy import select, delete
from app.core.database import AsyncSessionLocal
from app.models.user import User
from app.core.logger import get_logger
logger = get_logger(__name__)
async def cleanup_users():
"""
删除除admin以外的所有用户
保留username='admin'的管理员账号
"""
async with AsyncSessionLocal() as db:
try:
# 查询要删除的用户
stmt = select(User).where(User.username != 'admin', User.is_deleted == False)
result = await db.execute(stmt)
users_to_delete = result.scalars().all()
if not users_to_delete:
logger.info("没有需要删除的用户")
return
logger.info(f"准备删除 {len(users_to_delete)} 个用户")
for user in users_to_delete:
logger.info(f" - ID: {user.id}, 用户名: {user.username}, 姓名: {user.full_name}")
# 确认删除
print("\n⚠️ 警告: 将删除以上用户保留admin")
confirm = input("确认删除?(yes/no): ")
if confirm.lower() != 'yes':
logger.info("取消删除操作")
return
# 执行软删除
for user in users_to_delete:
user.is_deleted = True
logger.info(f"已软删除用户: {user.username}")
await db.commit()
logger.info(f"✅ 成功删除 {len(users_to_delete)} 个用户")
# 显示剩余用户
stmt = select(User).where(User.is_deleted == False)
result = await db.execute(stmt)
remaining_users = result.scalars().all()
logger.info(f"\n剩余用户数量: {len(remaining_users)}")
for user in remaining_users:
logger.info(f" - ID: {user.id}, 用户名: {user.username}, 角色: {user.role}")
except Exception as e:
logger.error(f"清理用户失败: {str(e)}")
await db.rollback()
raise
if __name__ == "__main__":
print("=" * 60)
print("用户清理脚本")
print("=" * 60)
asyncio.run(cleanup_users())