在Flask中生成动态Pygal图表

1 投票
2 回答
5867 浏览
提问于 2025-04-18 16:29

我正在尝试创建一个Pygal图表,并在Flask中显示它——而不保存.svg文件。这样做可能吗?我尝试的每种组合都给我带来了错误。

{% extends "base.html" %}
{% block content %} {{chart}} {% endblock %}

视图:

@app.route('/chart')
def test():
bar_chart = pygal.HorizontalStackedBar()
bar_chart.title = "Remarquable sequences"
bar_chart.x_labels = map(str, range(11))
bar_chart.add('Fibonacci', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55])
bar_chart.add('Padovan', [1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12]) 
chart = bar_chart.render()
return render_template('test.html', chart=chart )

有没有人能告诉我我哪里做错了?

2 个回答

3
import pygal

@app.route('/something.svg')
def graph_something():
    bar_chart = pygal.Bar()
    bar_chart.add('Fibonacci', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55])
    return bar_chart.render_response()
<body>
  <figure>
    <embed type="image/svg+xml" src="/mysvg.svg" />
  </figure>
</body>

然后只需要让你的html文件引用那个文件就可以了:

8

如果你在使用Python 2.7,你需要这样做:

@app.route('/chart')
def test():
    bar_chart = pygal.HorizontalStackedBar()
    bar_chart.title = "Remarquable sequences"
    bar_chart.x_labels = map(str, range(11))
    bar_chart.add('Fibonacci', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55])
    bar_chart.add('Padovan', [1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12]) 
    chart = bar_chart.render(is_unicode=True)
    return render_template('test.html', chart=chart )

然后在模板中显示图表:

{% extends "base.html" %}
{% block content %} {{chart|safe}} {% endblock %}

撰写回答