Python の Web アプリ化 (Dash)

2023年6月20日

はじめに

Dash は Python を Web アプリ化するライブラリ (というより、Python で Web アプリを作成するライブラリ) である。Plotly の関連プロジェクトのようである。

バージョン

  • Windows 10 64bit
  • Python 3.11.3

インストール

インストールは pip で行う。

>pip install dash

そのうち pandas が要求されるので入れておく。

>pip install pandas

例

minimal_app.py

from dash import Dash, html, dcc, callback, Output, Input
import plotly.express as px
import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')

app = Dash(__name__)

app.layout = html.Div([
    html.H1(children='Title of Dash App', style={'textAlign':'center'}),
    dcc.Dropdown(df.country.unique(), 'Canada', id='dropdown-selection'),
    dcc.Graph(id='graph-content')
])

@callback(
    Output('graph-content', 'figure'),
    Input('dropdown-selection', 'value')
)
def update_graph(value):
    dff = df[df.country==value]
    return px.line(dff, x='year', y='pop')

if __name__ == '__main__':
    app.run_server(debug=True)

実行

>python minimal_app.py
Dash is running on http://127.0.0.1:8050/

ブラウザで表示されるアドレスにアクセスすればよい。

アプリ例

平方根計算

sqrt.py

from dash import Dash, dcc, html, Input, Output, State, callback

app = Dash(__name__)

app.layout = html.Div([
    html.H1("平方根計算"),
    dcc.Input(id="input_text", placeholder="数値を入力"),
    html.Button("計算", id="submit_value"),
    html.Div(id="output_value", children="")
])

def sqrt(a):
    if a <= 0: return 0
    x = 1.
    for i in range(10):
        x = x - (x**2 - a)/(2.*x)
    return x

@callback(
    Output("output_value", "children"),
    Input("submit_value", "n_clicks"),
    State("input_text", "value")
)
def update_output(n_clicks, value):
    try:
        a = float(value)
        x = sqrt(a)
        return str(x)
    except:
        return ""

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

感想

DOM の知識を要求されるので、少しツラい。