用Python Flask将字典列表传递给.js文件以创建Highcharts

39 阅读1分钟

我正在尝试将字典列表传递给.js文件,以便使用Python Flask创建Highcharts。我想传递键值对到堆叠柱状图的x轴和y轴。

以下是我尝试过的代码:

app.py:

typeuser_dict=[{u'dave': [163, 330, 17, datetime.datetime(2018, 7, 20, 0, 0)]}]

return render_template('profile.html', typeuser_dict=typeuser_dict)

barchart.js:

Highcharts.chart('container', {
chart: {
  type: 'column'
},
title: {
  text: 'Stacked column chart'
},
xAxis: {
  categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
},
yAxis: {
  min: 0,
  title: {
    text: 'Total fruit consumption'
  },
  stackLabels: {
    enabled: true,
    style: {
      fontWeight: 'bold',
      color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
    }
  }
},
legend: {
  align: 'right',
  x: -30,
  verticalAlign: 'top',
  y: 25,
  floating: true,
  backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
  borderColor: '#CCC',
  borderWidth: 1,
  shadow: false
},
tooltip: {
  headerFormat: '<b>{point.x}</b><br/>',
  pointFormat: '{series.name}: {point.y}<br/>Total: {point.stackTotal}'
},
plotOptions: {
  column: {
    stacking: 'normal',
    dataLabels: {
      enabled: true,
color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white'
    }
  }
},
series: [{
  name: 'A',
  data: [5, 3, 4, 7, 2]
}, {
  name: 'J',
  data: [2, 2, 3, 2, 1]
}, {
  name: 'Z',
  data: [3, 4, 4, 2, 5]
}]});

2、解决方案

为了解决这个问题,我们需要在Python代码中对字典列表进行格式化,使其符合Highcharts所需的格式。然后,我们可以在.js文件中使用这些格式化的数据来创建Highcharts图表。

以下是我修改后的代码:

app.py:

# 格式化字典列表
formatted_data = []
for user, data in typeuser_dict.items():
    formatted_data.append({'name': user, 'data': data})

return render_template('profile.html', typeuser_dict=formatted_data)

barchart.js:

// 获取格式化后的数据
var data = {{ typeuser_dict|tojson }};

// 创建Highcharts图表
Highcharts.chart('container', {
chart: {
  type: 'column'
},
title: {
  text: 'Stacked column chart'
},
xAxis: {
  categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
},
yAxis: {
  min: 0,
  title: {
    text: 'Total fruit consumption'
  },
  stackLabels: {
    enabled: true,
    style: {
      fontWeight: 'bold',
      color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
    }
  }
},
legend: {
  align: 'right',
  x: -30,
  verticalAlign: 'top',
  y: 25,
  floating: true,
  backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
  borderColor: '#CCC',
  borderWidth: 1,
  shadow: false
},
tooltip: {
  headerFormat: '<b>{point.x}</b><br/>',
  pointFormat: '{series.name}: {point.y}<br/>Total: {point.stackTotal}'
},
plotOptions: {
  column: {
    stacking: 'normal',
    dataLabels: {
      enabled: true,
      color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white'
    }
  }
},
series: data // 使用格式化后的数据创建系列
});

通过这种方法,我们可以将格式化后的字典列表传递给.js文件,并使用这些数据创建Highcharts图表。