Search code examples
pythonflaskpygal

Generating Dynamic Pygal Chart in Flask


I am trying to create a Pygal chart and display it in flask - without saving the .svg file. Is this possible? Every Combination i have tried has given me an error. template:

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

Views:

@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 )

Can anyone tell me what I am doing wrong?


Solution

  • If you are using Python 2.7 you will need to use this:

    @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 )
    

    And to render the graph in the template:

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