金子邦彦研究室プログラミングPython による Web アプリの見本(Dash, Flash を使用)Dash のインストールと動作確認

Dash のインストールと動作確認

ユースケース:Web でグラフや表を簡単に表示したい。そして、ユーザ側で操作ができるようにしたい。

サイト内の関連ページ

参考Webページ

前準備

Python の準備(Windows,Ubuntu 上)

サイト内の関連ページ

関連する外部ページ

Python の公式ページ: https://www.python.org/

Dash のインストール, 動作確認

Python パッケージをインストールする

  1. Windows で,コマンドプロンプト管理者として実行

    コマンドプロンプトを管理者として実行: 別ページ »で説明

  2. dash, dash-daq のインストール

    https://dash.plot.ly/installation の記述による

  3. 試しに Dash を動かしてみる
    1. Python プログラムの作成

      Windows の場合, コマンドプロンプトで次を実行

      cd %HOMEPATH%
      notepad hoge.py
      

      次のようなPython プログラムをhoge.pyのようなファイル名で保存

      # -*- coding: utf-8 -*-
      import dash
      import dash_core_components as dcc
      import dash_html_components as html
      
      external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
      
      app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
      
      app.layout = html.Div(children=[
          html.H1(children='Hello Dash'),
      
          html.Div(children='''
              Dash: A web application framework for Python.
          '''),
      
          dcc.Graph(
              id='example-graph',
              figure={
                  'data': [
                      {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'},
                      {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montral'},
                  ],
                  'layout': {
                      'title': 'Dash Data Visualization'
                  }
              }
          )
      ])
      
      if __name__ == '__main__':
          app.run_server(debug=True)
      
    2. Python プログラムの実行

      Python プログラムの実行: 別ページ »で説明

      Python のまとめ: 別ページ »にまとめ

    3. Web ブラウザで、localhost:8050 を開く。次のような画面が出れば、動作OK

      [image]

Dash の中身を 定期的に更新するプログラム

注意点

プログラムのポイント

# -*- coding: utf-8 -*-
import dash
import dash_table
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd

import time
import threading

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

L = [[1, 2, 3], [4, 1, 2]]
X = pd.DataFrame(L)

def do_layout():
    global app
    app.layout = html.Div(children=[
        html.H1(children='Hello Dash'),
    
        html.Div(children='''
            Dash: A web application framework for Python.
        '''),
    
        dash_table.DataTable(
            id='table',
            columns=[ {"name": i, "id": i} for i in X.columns], 
            data=X.to_dict("rows")
        )
    ])

import time
import threading

# 定期的に繰り返すスレッド
def worker():
    global X
    do_layout() 
    print(time.gmtime())
    X[0][0] = X[0][0] + 1
    print(X[0][0]) 
# 動作試験のため、わざと 8 秒待つようにしている
    time.sleep(8)

def mainloop():
# 5秒間隔
    time_interval = 5
    now = time.time()
    while True:
        t = threading.Thread(target=worker)
        t.start()
        t.join() 
        wait_time = time_interval - ( (time.time() - now) % time_interval )
        print(wait_time) 
        time.sleep(wait_time)


if __name__ == '__main__':    t0 = threading.Thread(target=mainloop)
    t0.start()
# マルチスレッドにしたい。debug は False で. (debug=True に変えたときの動作は確認していません)
    app.run_server(debug=False)