fix_user_names.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. """修复 user 表中因连接未使用 utf8mb4 而变成 ?? 的姓名(与 sql/init_db.sql 种子一致)。"""
  2. import os
  3. import sys
  4. ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  5. if ROOT not in sys.path:
  6. sys.path.insert(0, ROOT)
  7. from app import create_app
  8. from app.config import mysql_uri_with_utf8mb4
  9. from app.models import User, db
  10. # user_id -> (first_name 名字, last_name 姓氏)
  11. NAMES = {
  12. 1: ('系统', '管理员'),
  13. 2: ('开发', '人员'),
  14. 3: ('演示', '用户'),
  15. }
  16. def main() -> None:
  17. uri = os.environ.get('SQLALCHEMY_DATABASE_URI')
  18. if uri:
  19. os.environ['SQLALCHEMY_DATABASE_URI'] = mysql_uri_with_utf8mb4(uri)
  20. app = create_app()
  21. with app.app_context():
  22. updated = 0
  23. for user_id, (first_name, last_name) in NAMES.items():
  24. user = db.session.get(User, user_id)
  25. if not user:
  26. continue
  27. if user.first_name == first_name and user.last_name == last_name:
  28. continue
  29. user.first_name = first_name
  30. user.last_name = last_name
  31. updated += 1
  32. print(f'user_id={user_id} ({user.username}): {first_name!r} / {last_name!r}')
  33. if updated:
  34. db.session.commit()
  35. print(f'已更新 {updated} 条用户姓名。')
  36. else:
  37. print('无需更新(姓名已正确)。')
  38. if __name__ == '__main__':
  39. main()