import_base_t.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import json
  2. import pymysql
  3. JSON_FILE = "base_templates.json"
  4. DB_CONFIG = {
  5. "host": "127.0.0.1",
  6. "user": "root",
  7. "password": "root",
  8. "database": "recycle",
  9. "charset": "utf8mb4",
  10. "cursorclass": pymysql.cursors.DictCursor
  11. }
  12. def remove_value_text(obj):
  13. """
  14. 递归删除所有 valueText 字段
  15. """
  16. if isinstance(obj, dict):
  17. obj.pop("valueText", None)
  18. for k, v in obj.items():
  19. remove_value_text(v)
  20. elif isinstance(obj, list):
  21. for item in obj:
  22. remove_value_text(item)
  23. def main():
  24. with open(JSON_FILE, "r", encoding="utf-8") as f:
  25. data = json.load(f)
  26. conn = pymysql.connect(**DB_CONFIG)
  27. try:
  28. with conn.cursor() as cursor:
  29. for template_id, template_data in data.items():
  30. # 深拷贝一份,避免污染原对象
  31. cleaned = json.loads(json.dumps(template_data))
  32. # 删除 valueText
  33. remove_value_text(cleaned)
  34. template_version = str(cleaned.get("templateVersion"))
  35. template_json = json.dumps(
  36. cleaned["template"],
  37. ensure_ascii=False
  38. )
  39. sql = """
  40. INSERT INTO base_estimate_template
  41. (template_id, template_version, template_json)
  42. VALUES (%s, %s, %s)
  43. ON DUPLICATE KEY UPDATE
  44. template_version = VALUES(template_version),
  45. template_json = VALUES(template_json)
  46. """
  47. cursor.execute(
  48. sql,
  49. (
  50. int(template_id),
  51. template_version,
  52. template_json
  53. )
  54. )
  55. print(f"导入模板 {template_id} 成功")
  56. conn.commit()
  57. finally:
  58. conn.close()
  59. if __name__ == "__main__":
  60. main()