PBI-Measure-CallGraph/app.py
2025-03-21 16:11:03 +08:00

98 lines
3.2 KiB
Python

from flask import Flask, render_template, jsonify, request
import json
import os
import requests
from model_connector import ModelConnector
from dax_parser import DaxParser
app = Flask(__name__)
# Initialize the model connector and DAX parser
model_connector = None
dax_parser = DaxParser()
@app.route('/')
def index():
"""Render the main page."""
return render_template('index.html')
@app.route('/connect', methods=['POST'])
def connect():
"""Connect to the Analysis Services model."""
global model_connector
data = request.json
server = data.get('server')
database = data.get('database')
try:
model_connector = ModelConnector(server, database)
return jsonify({'success': True, 'message': 'Connected successfully'})
except Exception as e:
return jsonify({'success': False, 'message': str(e)})
@app.route('/get_measures')
def get_measures():
"""Get all measures from the connected model."""
if not model_connector:
return jsonify({'success': False, 'message': 'Not connected to a model'})
try:
measures = model_connector.get_measures()
return jsonify({'success': True, 'measures': measures})
except Exception as e:
return jsonify({'success': False, 'message': str(e)})
@app.route('/get_call_graph')
def get_call_graph():
"""Generate and return the call graph data."""
if not model_connector:
return jsonify({'success': False, 'message': 'Not connected to a model'})
try:
measures_df = model_connector.get_measures()
measures = measures_df.to_dict(orient="records")
graph = dax_parser.build_call_graph(measures)
return jsonify({'success': True, 'graph': graph})
except Exception as e:
return jsonify({'success': False, 'message': str(e)})
@app.route('/format_dax', methods=['POST'])
def format_dax():
"""Proxy for DAX formatter service."""
try:
dax_code = request.json.get('daxCode')
if not dax_code:
return jsonify({'success': False, 'message': 'No DAX code provided'})
# 调用新的DAX格式化API
payload = {
'dax': dax_code,
'callerApp': 'https://www.daxformatter.com/',
'callerVersion': '0.5.3',
'listSeparator': ',',
'decimalSeparator': '.',
'maxLineLength': 0
}
response = requests.post('https://daxformatter.azurewebsites.net/api/DaxTokenFormat/',
json=payload)
if response.status_code != 200:
return jsonify({'success': False, 'message': 'DAX formatting service error'})
# 解析返回的JSON
formatted_data = response.json()
# 检查是否有错误
if formatted_data.get('errors') and len(formatted_data['errors']) > 0:
return jsonify({'success': False, 'message': 'DAX formatting error: ' + str(formatted_data['errors'])})
return jsonify({'success': True, 'formattedTokens': formatted_data['formatted']})
except Exception as e:
return jsonify({'success': False, 'message': str(e)})
if __name__ == '__main__':
app.run(debug=True)