import_base_template.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import json
  2. import pymysql
  3. DB_CONFIG = {
  4. "host": "127.0.0.1", # 如果在 docker 里,请改成 mysql 服务名
  5. "user": "root",
  6. "password": "root",
  7. "database": "recycle",
  8. "charset": "utf8mb4"
  9. }
  10. def remove_value_text(obj):
  11. """
  12. 递归删除所有 valueText 字段
  13. """
  14. if isinstance(obj, dict):
  15. obj.pop("valueText", None)
  16. for k, v in obj.items():
  17. remove_value_text(v)
  18. elif isinstance(obj, list):
  19. for item in obj:
  20. remove_value_text(item)
  21. def main():
  22. with open("base_templates.json", "r", encoding="utf-8") as f:
  23. data = json.load(f)
  24. conn = pymysql.connect(**DB_CONFIG)
  25. cursor = conn.cursor()
  26. sql = """
  27. INSERT INTO base_estimate_template
  28. (id, name, template_json, template_version, remark)
  29. VALUES
  30. (%s, %s, %s, %s, %s)
  31. ON DUPLICATE KEY UPDATE
  32. name = VALUES(name),
  33. template_json = VALUES(template_json),
  34. template_version = VALUES(template_version),
  35. remark = VALUES(remark)
  36. """
  37. for tpl_id, tpl_data in data.items():
  38. template_id = int(tpl_id)
  39. name = f"基础模板-{template_id}"
  40. # 深拷贝一份,避免污染原对象
  41. cleaned = json.loads(json.dumps(tpl_data))
  42. # 删除 valueText
  43. remove_value_text(cleaned)
  44. template_version = str(cleaned.get("templateVersion", 1))
  45. template_json = json.dumps(
  46. cleaned["template"],
  47. ensure_ascii=False
  48. )
  49. # 优先使用 JSON 内的 templateVersion
  50. # version = tpl_data.get("templateVersion", 1)
  51. remark = "import from json file"
  52. cursor.execute(
  53. sql,
  54. (
  55. template_id,
  56. name,
  57. template_json,
  58. int(template_version),
  59. remark
  60. )
  61. )
  62. print(f"insert template {template_id}")
  63. conn.commit()
  64. cursor.close()
  65. conn.close()
  66. if __name__ == "__main__":
  67. main()