init_data.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. """
  2. 数据初始化脚本
  3. 从模型列表.json文件导入数据到数据库
  4. 需求: 5.1, 5.2, 5.3, 5.4, 5.5
  5. """
  6. import json
  7. import sys
  8. from pathlib import Path
  9. sys.path.insert(0, str(Path(__file__).parent.parent))
  10. from app.database import SessionLocal
  11. from app.models.model import ModelNew
  12. def init_data():
  13. """初始化模型数据"""
  14. json_path = Path(__file__).parent.parent.parent / "模型列表.json"
  15. with open(json_path, 'r', encoding='utf-8') as f:
  16. models_data = json.load(f)
  17. db = SessionLocal()
  18. inserted = 0
  19. updated = 0
  20. for item in models_data:
  21. existing = db.query(Model).filter(Model.title == item['title']).first()
  22. if existing:
  23. existing.img = item.get('img', '')
  24. existing.name = item.get('name', '')
  25. existing.tag1 = item.get('tag1', '')
  26. existing.description = item.get('description', '')
  27. existing.keyword = item.get('keyword', '')
  28. existing.time = item.get('time', '')
  29. existing.tag2 = item.get('tag2', '')
  30. updated += 1
  31. else:
  32. model = Model(
  33. title=item['title'],
  34. img=item.get('img', ''),
  35. name=item.get('name', ''),
  36. tag1=item.get('tag1', ''),
  37. description=item.get('description', ''),
  38. keyword=item.get('keyword', ''),
  39. time=item.get('time', ''),
  40. tag2=item.get('tag2', '')
  41. )
  42. db.add(model)
  43. inserted += 1
  44. db.commit()
  45. db.close()
  46. print(f"数据导入完成: 新增 {inserted} 条, 更新 {updated} 条, 共 {inserted + updated} 条")
  47. if __name__ == "__main__":
  48. init_data()