routes.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. import json
  2. import logging
  3. from flask import request, jsonify
  4. from app.api.production_line import bp
  5. from app.models.result import success, failed
  6. from app.api.graph.routes import MyEncoder, connect_graph
  7. from app.core.production_line import production_draw_graph
  8. from app.core.production_line.production_line import execute_production_line
  9. logger = logging.getLogger(__name__)
  10. # 生产线列表
  11. @bp.route('/production/line/list', methods=['POST'])
  12. def production_line_list():
  13. """
  14. 获取生产线列表,支持分页和名称过滤
  15. Args (通过JSON请求体):
  16. current (int): 当前页码,默认为1
  17. size (int): 每页大小,默认为10
  18. name (str, optional): 名称过滤条件
  19. Returns:
  20. JSON: 包含生产线列表和分页信息的响应
  21. """
  22. try:
  23. receiver = request.get_json()
  24. page = int(receiver.get('current', 1))
  25. page_size = int(receiver.get('size', 10))
  26. name_filter = receiver.get('name', None)
  27. # 计算跳过的记录的数量
  28. skip_count = (page - 1) * page_size
  29. if name_filter:
  30. where_clause = f"n.name CONTAINS'{name_filter}'"
  31. else:
  32. where_clause = "TRUE"
  33. cql = f"""
  34. MATCH (n)
  35. WHERE (n:data_model OR n:data_resource OR n:data_metric) AND {where_clause}
  36. WITH id(n) AS id, n.name AS name, labels(n)[0] AS type,n
  37. RETURN {{
  38. id: id,
  39. name: name,
  40. type: type
  41. }} AS result,n.time as time
  42. ORDER BY time desc
  43. SKIP {skip_count}
  44. LIMIT {page_size}
  45. """
  46. data = connect_graph.run(cql).data()
  47. records = []
  48. for item in data:
  49. records.append(item['result'])
  50. # 获取总量
  51. total_query = f"MATCH (n) WHERE (n:data_model OR n:data_resource OR n:data_metric) AND {where_clause}" \
  52. f" RETURN COUNT(n) AS total"
  53. total_result = connect_graph.run(total_query).evaluate()
  54. response_data = {'records': records, 'total': total_result, 'size': page_size, 'current': page}
  55. res = success(response_data, "success")
  56. return json.dumps(res, ensure_ascii=False, cls=MyEncoder)
  57. except Exception as e:
  58. res = failed({}, {"error": f"{e}"})
  59. return json.dumps(res, ensure_ascii=False, cls=MyEncoder)
  60. # 根据生产线列表,传入id,绘制图谱
  61. @bp.route('/production/line/graph', methods=['POST'])
  62. def production_line_graph():
  63. """
  64. 根据生产线ID绘制关系图谱
  65. Args (通过JSON请求体):
  66. id (int): 节点ID
  67. Returns:
  68. JSON: 包含图谱数据的响应
  69. """
  70. # 传入请求参数
  71. receiver = request.get_json()
  72. id = receiver['id']
  73. try:
  74. cql = """
  75. MATCH (n) where id(n) = $nodeId return labels(n)[0] as type
  76. """
  77. type = connect_graph.run(cql, nodeId=id).evaluate()
  78. data = production_draw_graph(id, type)
  79. res = success(data, "success")
  80. return json.dumps(res, ensure_ascii=False, cls=MyEncoder)
  81. except Exception as e:
  82. res = failed({}, {"error": f"{e}"})
  83. return json.dumps(res, ensure_ascii=False, cls=MyEncoder)
  84. """
  85. Manual execution API endpoint
  86. Author: paul
  87. Date: 2024-03-20
  88. """
  89. @bp.route('/production/line/execute', methods=['POST'])
  90. def production_line_execute():
  91. """
  92. 手动执行数据资源加载
  93. Args (通过JSON请求体):
  94. id (int): 数据资源ID
  95. Returns:
  96. JSON: 执行结果
  97. """
  98. try:
  99. # 获取资源ID
  100. resource_id = request.json.get('id')
  101. if resource_id is None: # 修改检查逻辑,只有当ID为None时才报错
  102. return jsonify(failed("资源ID不能为空"))
  103. # 执行加载
  104. result = execute_production_line(resource_id)
  105. if result['status'] == 'success':
  106. return jsonify(success(result))
  107. else:
  108. return jsonify(failed(result['message']))
  109. except Exception as e:
  110. logger.error(f"执行数据资源加载失败: {str(e)}")
  111. return jsonify(failed(str(e)))