Python-web-development-libraries-dash-framework

提供:Dev Guides
移動先:案内検索

ダッシュフレームワーク

この章では、Dashフレームワークについて詳しく説明します。

Dashは、分析Webアプリケーションの構築に使用されるオープンソースのPythonフレームワークです。 これは、データ駆動型アプリケーションの開発を簡素化する強力なライブラリです。 これは、Web開発にあまり詳しくないPythonデータ科学者にとって特に便利です。 ユーザーはダッシュを使用してブラウザで素晴らしいダッシュボードを作成できます。

Plotly.js、React、およびFlaskの上に構築されたDashは、ドロップダウン、スライダー、グラフなどの最新のUI要素を分析Pythonコードに直接結び付けます。

ダッシュアプ​​リは、HTTP要求でJSONパケットを使用してフロントエンドのReactコンポーネントと通信するFlaskサーバーで構成されます。

ダッシュアプ​​リケーションは純粋にPythonで記述されているため、HTMLやJavaScriptは必要ありません。

ダッシュのセットアップ

端末にDashがまだインストールされていない場合は、下記のDashライブラリをインストールします。 これらのライブラリは活発に開発されているため、頻繁にインストールしてアップグレードしてください。 Python 2および3もサポートされています。

  • pip install dash == 0.23.1#コアダッシュバックエンド
  • pip install dash-renderer == 0.13.0#ダッシュフロントエンド
  • pip install dash-html-components == 0.11.0#HTMLコンポーネント
  • pip install dash-core-components == 0.26.0#過給コンポーネント
  • pip install plotly == 3.1.0#Plotly graphing library

すべてが正常に機能していることを確認するために、ここでは単純なdashApp.pyファイルを作成しました。

ダッシュまたはアプリのレイアウト

ダッシュアプ​​リは2つの部分で構成されています。 最初の部分は、基本的にアプリケーションがどのように見えるかを説明するアプリの「レイアウト」です。 2番目の部分では、アプリケーションの対話性について説明します。

コアコンポーネント

*dash_html_components* および *dash_core_components* ライブラリを使用してレイアウトを構築できます。 Dashは、アプリケーションのすべての視覚コンポーネントにPythonクラスを提供します。 JavaScriptとReact.jsを使用して独自のコンポーネントをカスタマイズすることもできます。

dash_core_componentsをdccとしてインポート

dash_html_componentsをhtmlとしてインポート

dash_html_componentsは、dash_core_componentsがReact.jsで作成された対話機能用であるすべてのHTMLタグ用です。

上記の2つのライブラリを使用して、以下のコードを記述しましょう-

app = dash.Dash()
app.layout = html.Div(children=[
   html.H1(children='Hello Dash'),
   html.Div(children='''Dash Framework: A web application framework for Python.''')

そして、同等のHTMLコードは次のようになります-

<div>
   <h1> Hello Dash </h1>
   <div> Dash Framework: A web application framework for Python. </div>
</div>

Simple Dashアプリの作成

ファイル dashApp.py で上記のライブラリを使用して、ダッシュで簡単な例を作成する方法を学習します。

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

app = dash.Dash()
app.layout = html.Div(children=[
   html.H1(children='Hello Dash'),
   html.Div(children='''Dash Framework: A web application framework for Python.'''),

   dcc.Graph(
      id='example-graph',
      figure={
         'data': [
            {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'Delhi'},
            {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Mumbai'},
         ],
         'layout': {
            'title': 'Dash Data Visualization'
         }
      }
   )
])

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

Dashアプリを実行する

Dashアプリの実行中は、次の点に注意してください。

(MyDjangoEnv)C:\ Users \ rajesh \ Desktop \ MyDjango \ dash> python dashApp1.py

  • Flaskアプリ「dashApp1」の提供(遅延読み込み)
  • 環境:生産

WARNING Do not use the development server in a production environment. +代わりに実稼働WSGIサーバーを使用します。 * デバッグモード:オン * statで再起動する * デバッガーがアクティブです! * デバッガーPIN:130-303-947 * http://127.0.0.1:8050/ で実行(終了するにはCTRL + Cを押してください)

127.0.0.1 - - [12/Aug/2018 09:32:39] "GET/HTTP/1.1" 200 -
127.0.0.1 - - [12/Aug/2018 09:32:42] "GET/_dash-layout HTTP/1.1" 200 -
127.0.0.1 - - [12/Aug/2018 09:32:42] "GET/_dash-dependencies HTTP/1.1" 200 -
127.0.0.1 - - [12/Aug/2018 09:32:42] "GET/favicon.ico HTTP/1.1" 200 -
127.0.0.1 - - [12/Aug/2018 09:39:52] "GET/favicon.ico HTTP/1.1" 200 -

Webブラウザで http:127.0.0.1:8050/ にアクセスします。 次のようなアプリが表示されます。

Hello Dash

上記のプログラムでは、注意すべきいくつかの重要な点は次のとおりです-

  • アプリのレイアウトは、html.Divやdcc.Graphのような「コンポーネント」のツリーで構成されています。
  • dash_html_componentsライブラリには、すべてのHTMLタグのコンポーネントがあります。 html.H1(children = ‘Hello Dash’)コンポーネントは、アプリケーションで<h1> Hello Dash </h1> HTML要素を生成します。
  • すべてのコンポーネントが純粋なHTMLではありません。 dash_core_componentsは、インタラクティブで、React.jsライブラリーを介してJavaScript、HTML、およびCSSで生成される高レベルのコンポーネントを記述します。
  • 各コンポーネントは、キーワード属性によって完全に記述されます。 ダッシュは宣言的です。主にこれらの属性を使用してアプリケーションを説明します。
  • childrenプロパティは特別です。 慣例により、常に最初の属性であるため、省略できます。
  • Html.H1(children = ’Hello Dash’)は、html.H1(「Hello Dash」)と同じです。
  • アプリケーションのフォントは、ここに表示されているものとは少し異なります。 このアプリケーションは、カスタムCSSスタイルシートを使用して、要素のデフォルトスタイルを変更しています。 カスタムフォントスタイルは許可されますが、現在のところ、以下のURLまたは任意のURLを追加できます- + app.css.append_css(\ {“ external_url”:* [[1]]

HTMLの詳細

dash_html_componentsライブラリには、すべてのHTMLタグのコンポーネントクラスと、すべてのHTML引数のキーワード引数が含まれています。

以前のアプリテキストにコンポーネントのインラインスタイルを追加しましょう-

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

app = dash.Dash()
colors = {
   'background': '#87D653',
   'text': '#ff0033'
}

app.layout = html.Div(style={'backgroundColor': colors['background']}, children=[
   html.H1(
      children='Hello Dash',
      style={
         'textAlign': 'center',
         'color': colors['text']
      }
   ),

   html.Div(children='Dash: A web application framework for Python.', style={
      'textAlign': 'center',
      'color': colors['text']
   }),

   dcc.Graph(
      id='example-graph-2',

      figure={
         'data': [
            {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'Delhi'},
            {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Mumbai'},
         ],
         'layout': {
            'plot_bgcolor': colors['background'],
            'paper_bgcolor': colors['background'],
            'font': {
               'color': colors['text']
            }
         }
      }
   )
])

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

上の例では、html.Divおよびhtml.H1コンポーネントのインラインスタイルをstyleプロパティで変更しました。

スタイルプロパティ

次のようにDashアプリケーションでレンダリングされます-

データアプリケーション

dash_html_componentsとHTML属性の間にいくつかの重要な違いがあります-

  • Dashのスタイルプロパティの場合、辞書を指定するだけで済みますが、HTMLの場合はセミコロンで区切られた文字列です。
  • スタイル辞書キーは camelCased であるため、テキストの配置は textalign に変更されます。
  • DashのClassNameは、HTMLクラス属性に似ています。
  • 最初の引数は、childrenキーワード引数で指定されたHTMLタグの子です。

再利用可能なコンポーネント

Pythonでマークアップを記述することにより、コンテキストや言語を切り替えることなく、テーブルのような複雑で再利用可能なコンポーネントを作成できます-

以下は、pandasデータフレームから「テーブル」を生成する簡単な例です。

import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd

df = pd.read_csv(
   'https://gist.githubusercontent.com/chriddyp/'
   'c78bf172206ce24f77d6363a2d754b59/raw/'
   'c353e8ef842413cae56ae3920b8fd78468aa4cb2/'
   'usa-agricultural-exports-2011.csv')

def generate_table(dataframe, max_rows=10):
   return html.Table(
      # Header
      [html.Tr([html.Th(col) for col in dataframe.columns])] +
      # Body
      [html.Tr([
         html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
      ]) for i in range(min(len(dataframe), max_rows))]
   )

app = dash.Dash()
app.layout = html.Div(children=[
   html.H4(children='US Agriculture Exports (2011)'),
   generate_table(df)
])

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

出力は次のようになります-

再利用可能なコンポーネント

視覚化の詳細

dash_core_componentsライブラリには、 Graph というコンポーネントが含まれています。

Graphは、オープンソースのplotly.js JavaScriptグラフ作成ライブラリを使用して、インタラクティブなデータ視覚化をレンダリングします。 Plotly.jsは約35のチャートタイプをサポートし、ベクター品質のSVGと高性能WebGLの両方でチャートをレンダリングします。

以下は、パンダのデータフレームから散布図を作成する例です-

import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go

app = dash.Dash()

df = pd.read_csv(
   'https://gist.githubusercontent.com/chriddyp/' +
   '5d1ea79569ed194d432e56108a04d188/raw/' +
   'a9f9e8076b837d541398e999dcbac2b2826a81f8/'+
   'gdp-life-exp-2007.csv')

app.layout = html.Div([
   dcc.Graph(
      id='life-exp-vs-gdp',
      figure={
         'data': [
            go.Scatter(
               x=df[df['continent'] == i]['gdp per capita'],
               y=df[df['continent'] == i]['life expectancy'],
               text=df[df['continent'] == i]['country'],
               mode='markers',
               opacity=0.7,
               marker={
                  'size': 15,
                  'line': {'width': 0.5, 'color': 'white'}
               },
               name=i
            ) for i in df.continent.unique()
         ],
         'layout': go.Layout(
            xaxis={'type': 'log', 'title': 'GDP Per Capita'},
            yaxis={'title': 'Life Expectancy'},
            margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
            legend={'x': 0, 'y': 1},
            hovermode='closest'
         )
      }
   )
])

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

上記のコードの出力は次のとおりです-

視覚化

これらのグラフはインタラクティブで応答性があります。 ポイントにカーソルを合わせて値を表示し、凡例項目をクリックしてトレースを切り替え、クリックしてドラッグしてズームし、シフトを押したままにして、クリックしてドラッグしてパンすることができます。

値下げ

dashはdash_html_componentsライブラリを介してHTMLフレーバーを公開しますが、コピーをHTMLで記述するのは面倒です。 テキストのブロックを作成するには、dash_core_componentsライブラリのMarkdownコンポーネントを使用できます。

コアコンポーネント

dash_core_componentsには、ドロップダウン、グラフ、マークダウン、ブロックなどの高レベルのコンポーネントのセットが含まれます。

他のすべてのDashコンポーネントと同様に、それらは完全に宣言的に記述されています。 構成可能なすべてのオプションは、コンポーネントのキーワード引数として使用できます。

以下は、利用可能なコンポーネントのいくつかを使用した例です-

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

app = dash.Dash()

app.layout = html.Div([
   html.Label('Dropdown'),
   dcc.Dropdown(
      options=[
         {'label': 'New York City', 'value': 'NYC'},
         {'label': u'Montréal', 'value': 'MTL'},
         {'label': 'San Francisco', 'value': 'SF'}
      ],
      value='MTL'
   ),

   html.Label('Multi-Select Dropdown'),
   dcc.Dropdown(
      options=[
         {'label': 'New York City', 'value': 'NYC'},
         {'label': u'Montréal', 'value': 'MTL'},
         {'label': 'San Francisco', 'value': 'SF'}
      ],
      value=['MTL', 'SF'],
      multi=True
   ),

   html.Label('Radio Items'),
   dcc.RadioItems(
      options=[
         {'label': 'New York City', 'value': 'NYC'},
         {'label': u'Montréal', 'value': 'MTL'},
         {'label': 'San Francisco', 'value': 'SF'}
      ],
      value='MTL'
   ),

   html.Label('Checkboxes'),
   dcc.Checklist(
      options=[
         {'label': 'New York City', 'value': 'NYC'},
         {'label': u'Montréal', 'value': 'MTL'},
         {'label': 'San Francisco', 'value': 'SF'}
      ],
      values=['MTL', 'SF']
   ),

   html.Label('Text Input'),
   dcc.Input(value='MTL', type='text'),

   html.Label('Slider'),
   dcc.Slider(
      min=0,
      max=9,
      marks={i: 'Label {}'.format(i) if i == 1 else str(i) for i in range(1, 6)},
      value=5,
   ),
], style={'columnCount': 2})

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

上記のプログラムからの出力は次のとおりです-

コアコンポーネント

ヘルプの呼び出し

ダッシュコンポーネントは宣言型です。 これらのコンポーネントの構成可能な要素はすべて、インストール中にキーワード引数として設定されます。 任意のコンポーネントのpythonコンソールでヘルプを呼び出して、コンポーネントとその利用可能な引数について詳しく知ることができます。 それらのいくつかを以下に示します-

>>> help(dcc.Dropdown)
Help on class Dropdown in module builtins:
class Dropdown(dash.development.base_component.Component)
| A Dropdown component.
| Dropdown is an interactive dropdown element for selecting one or more

| items.
| The values and labels of the dropdown items are specified in the `options`
| property and the selected item(s) are specified with the `value` property.
|
| Use a dropdown when you have many options (more than 5) or when you are
| constrained for space. Otherwise, you can use RadioItems or a Checklist,
| which have the benefit of showing the users all of the items at once.
|
| Keyword arguments:
| - id (string; optional)
| - options (list; optional): An array of options
| - value (string | list; optional): The value of the input. If `multi` is false (the default)
-- More --

要約すると、Dashアプリのレイアウトはアプリの外観を説明します。 レイアウトは、コンポーネントの階層ツリーです。 dash_html_componentsライブラリは、すべてのHTMLタグとキーワード引数のクラスを提供し、style、className、idなどのHTML属性を記述します。 dash_core_componentsライブラリは、コントロールやグラフなどの高レベルのコンポーネントを生成します。