1. 程式人生 > >【python系列】python畫報表(Chartkick、Flask)(附中文亂碼解決方案)

【python系列】python畫報表(Chartkick、Flask)(附中文亂碼解決方案)

chartkick 可以畫 javascript 報表, 而且比較美觀。但是網上搜了下,很難找到 python 版本的,於是查了些資料,摸索了下。

對 Flask 也不很熟悉,這裡就只拋磚引玉了,如果有對這方面比較熟悉,還希望能貼點資料的連結。

chartkick簡介

Chartkick是一個圖表繪製工具,特點是UI美觀、使用簡單,並且支援IE6在內的大多數瀏覽器。之所以說它使用簡單,是因為只需要一行Ruby程式碼即可繪製出漂亮的圖表! 

Flask簡介

Flask是一個輕量級的Web應用框架, 使用Python編寫。基於 WerkzeugWSGI工具箱和 Jinja2模板引擎。使用 BSD 授權。

程式碼結構


run.py

from flask import Flask, jsonify, render_template, request
import chartkick

app = Flask(__name__, static_folder=chartkick.js())
app.jinja_env.add_extension("chartkick.ext.charts")

@app.route('/')
@app.route('/index')
def index():
    data = {'Chrome': 52.9, 'Opera': 1.6, 'Firefox': 27.7}
    return render_template('index.html', data=data)


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


index.html

index.html需要放在templates資料夾下 內容為
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="{{ url_for('static', filename='chartkick.js') }}"></script>

{% bar_chart data with style="width:200px; height:20px;" %}
{% pie_chart data %}


效果

執行run.py,然後訪問所顯示的地址
這裡為 http://127.0.0.1:5000/ 網頁內容為

中文亂碼解決方案

用 json 的 dumps 方法 將 dict 或者 list 轉換成可以正常顯示的中文字串。 其中 
return render_template('index.html', data=data)
可以換成
return render_template('index.html', data=cCode.str(data))

參考資料