使用flask和echart将值从python传递到html

时间:2019-07-05 13:12:41

标签: python html flask

我想将两个列表从.py文件传递到html,以使用html show on the web创建图表

xxx.py文件的代码:

from flask import Flask,render_template,request

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/conn',methods=['POST'])
def conn():
    table_name = request.form['table_name']  
    start_date = request.form['start_date']
    end_date = request.form['end_date']
    data1 = postgresql.PostgreSql(table_name,start_date,end_date)
    data1.rfm_chart()
    segment = data1.rfm['Segment'].value_counts().to_dict()
    return render_template('chart.html', **segment)

if __name__ == '__main__':
    app.run(debug=True)

段的输出:{'A':100,'B':50,'C':25,'D':18}

这是chart.html:

<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
    var myChart = echarts.init(document.getElementById('main'));

    var option = {
        title: {
            text: 'RFM'
        },
        tooltip: {},
        legend: {
            data:['Number of players']
        },
        xAxis: {
            data: {{  }}
        },
        yAxis: {},
        series: [{
            name: '#Players',
            type: 'bar',
            data: {{  }}
        }]
    };

    myChart.setOption(option);
</script>

我希望segment的键是x轴,值是y轴。但是如何将dict从.py传递到html?

1 个答案:

答案 0 :(得分:1)

您快到了,只需使用

之类的tojson过滤器
data: {{ series_data|tojson }}

您需要将series_data更改为您需要使用的密钥segment

http://jinja.pocoo.org/docs/2.10/templates/#tojson