「PythonとJavaScriptではじめるデータビジュアライゼーション」を読む

12.1 データ配信

#nobel_viz.py
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello world!"

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

nobel_viz.pyがあるフォルダで
$ python nobel_viz.py
と実行させると

d-js/data$ python nobel_viz.py 
 * Running on http://127.0.0.1:8000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 186-114-981

と表示され待機状態になる。
Webブラウザのアドレス欄にhttp://localhost:8000と入力して
アクセスさせるとHello world!と表示される。  

Jinja2を使ったテンプレート
フォルダ構成
nobel_viz.py  
  templates/  
    testj2.html  


from flask import Flask,render_template

app = Flask(__name__)
winners = [
    {'name':'Albert Einstein','category':'Physics'},
    {'name':'V. S. Naipaul','category':'Literature'},
    {'name':'Dorothy Hodgkin','category':'Chemistry'}
]

@app.route("/")
def hello():
    return "Hello world!"

@app.route("/demolist")
def demo_list():
    return render_template('testj2.html',heading="A little winners list",winners = winners)

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

#testj2.html
<!DOCTYPE html>
<meta charset="utf-8">
<body>
    <h2>{{ heading }}</h2> #/があるとエラーがでるので除外した
    <ul>
        {% for winner in winners %}
        <li><a href="{{ 'http://wikipedia.com/wiki/'+winner.name }}">
        {{ winner.name }}</a>
        {{ ', category: ' + winner.category}}
        </li>
        {% endfor %}
    </ul>
</body>

nobel_viz.pyがあるフォルダで python nobel_viz.pyと実行
さきほどと同じように待機状態になる

Webブラウザのアドレス欄にhttp://localhost:8000/demolistと入力して
アクセスさせると

f:id:bitop:20171014113946p:plain

となる。リンク先をクリックさせるとWikiに飛んでいく。