如何将python和google图表与microsoftsqlserver数据连接起来?

2024-04-26 17:29:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经用HTML和javascript编写了以下代码。我正在尝试创建一个饼图,其中包含通过python从microsoftsqlserver提取的数据。我写了以下代码

我试着用HTML呈现google图表,效果很好。我还能够将数据从microsoftsqlserver拉到python。当我试图从javascript调用python文件时,问题就出现了。你知道吗

JS代码:

 function drawChart(snapshot_dt, mnth) {

    // Create the data table.
    if(snapshot_dt == 'May' & mnth == 'Apr'){
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Status');
    data.addColumn('number', 'Number of Projects');

   data.addRows([
      ['On Schedule', 30],
      ['Pushed', 29],
      ['Accelerated', 20]
    ]);

    // Set chart options
    var options = {title:'Project Distribution for ' + mnth + ' and snapshot dt ' + snapshot_dt,
                   width:500,
                   height:250,
                   colors: ['#36CAAB', '#CFD4D8', '#49A9EA']};

    // Instantiate and draw our chart, passing in some options.
    //document.getElementById('pie_chart_title').innerHTML = options.title;
    var chart = new google.visualization.PieChart(document.getElementById('chart_div'));

    function selectHandler() {
      var selectedItem = chart.getSelection()[0];
      if (selectedItem) {
        var value = data.getValue(selectedItem.row, 1);
        alert('The user selected value is ' + value);
        drawChartTable();
      }
    }

    google.visualization.events.addListener(chart, 'select', selectHandler);    
    chart.draw(data, options);
  }
  else{
document.getElementById("chart_div").innerHTML = "";
}
}

下面是python代码:

    import pyodbc 
    import pandas as pd
    import json

     config = dict(server =   'falcondev', 
          port =      '####',                 
          database = '*****',
          username = '*****',
          password = '*****')

     #creating the connection string                                    
     conn_str = ('SERVER={server},{port};'   
        'DATABASE={database};'      
        'UID={username};'           
        'PWD={password}')


        # cursor for calling commands

          try:
conn = pyodbc.connect(r'DRIVER={' + pyodbc.drivers()[0] + '};' + conn_str.format(**config))  #this instruction to read the system ODBC driver version does not work in a Linux environment 
cursor = conn.cursor()
      except:
        print "Could not connect to Database"

             query = 'select [On Schedule],[Pushed],[Accelerated] from [iris].[dbo].[pie_test] where Effective_Month = \'Jan\' and Snapshot_Month = \'May\''
      df = pd.read_sql(query, con=conn) 

     a=df.to_json(orient='records')

如何从javascript调用python文件,以及如何格式化JSON,以便javascript函数在呈现图表时接受它?你知道吗


Tags: andthe代码datatitlevargooglechart