Python Web Development Libraries 简明教程
Dash Framework
在本章中,我们将详细讨论 Dash 框架。
In this chapter, we will discuss about the Dash framework in detail.
Dash 是一个用于构建分析性 Web 应用程序的开源 Python 框架。它是一个强大的库,简化了数据驱动的应用程序的开发。对于那些不太熟悉 Web 开发的 Python 数据科学家而言,它特别有用。用户可以使用 Dash 在其浏览器中创建出色的仪表板。
Dash is an open-source Python framework used for building analytical web applications. It is a powerful library that simplifies the development of data-driven applications. It’s especially useful for Python data scientists who aren’t very familiar with web development. Users can create amazing dashboards in their browser using dash.
基于 Plotly.js、React 和 Flask 构建,Dash 将现代 UI 元素(如下拉菜单、滑块和图形)直接连接到您的分析 Python 代码。
Built on top of Plotly.js, React, and Flask, Dash ties modern UI elements like dropdowns, sliders and graphs directly to your analytical python code.
Dash 应用程序包括一个 Flask 服务器,该服务器使用 HTTP 请求通过 JSON 数据包与前端 React 组件通信。
Dash apps consist of a Flask server that communicates with front-end React components using JSON packets over HTTP requests.
Dash 应用程序完全用 Python 编写,因此不需要 HTML 或 JavaScript。
Dash applications are written purely in python, so NO HTML or JavaScript is necessary.
Dash Setup
如果您的终端中尚未安装 Dash,请安装下面提到的 Dash 库。由于这些库处于活动开发阶段,因此请经常安装和升级库。Python 2 和 3 也受支持。
If Dash is not already installed in your terminal, then install the below mentioned Dash libraries. As these libraries are under active development, install and upgrade then frequently. Python 2 and 3 are also supported.
-
pip install dash==0.23.1 # The core dash backend
-
pip install dash-renderer==0.13.0 # The dash front-end
-
pip install dash-html-components==0.11.0 # HTML components
-
pip install dash-core-components==0.26.0 # Supercharged components
-
pip install plotly==3.1.0 # Plotly graphing library
为了确保一切正常工作,我们在这里创建了一个简单的 dashApp.py 文件。
In order to make sure everything is working properly, here, we created a simple dashApp.py file.
Dash or App Layout
Dash 应用程序由两部分组成。第一部分是应用程序的“布局”,它基本上描述了应用程序的外观。第二部分描述了应用程序的交互性。
Dash apps are composed of two parts. The first part is the “layout” of the app which basically describes how the application looks like. The second part describes the interactivity of the application.
Core Components
我们可以用 dash_html_components 和 dash_core_components 库构建布局。Dash 提供了应用程序所有可视化组件的 Python 类。我们还可以用 JavaScript 和 React.js 来自定义我们自己的组件。
We can build the layout with the dash_html_components and the dash_core_components library. Dash provides python classes for all the visual components of the application. We can also customize our own components with JavaScript and React.js.
import dash_core_components as dcc
import dash_html_components as html
dash_html_components 是用于所有 HTML 标签的,而 dash_core_components 用于使用 React.js 构建的交互性。
The dash_html_components is for all HTML tags where the dash_core_components is for interactivity built with React.js.
使用上述这两个库,我们来编写如下所示的代码:
Using above two libraries, let us write a code as given below −
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 代码将类似如下所示:
And the equivalent HTML code would look like this −
<div>
<h1> Hello Dash </h1>
<div> Dash Framework: A web application framework for Python. </div>
</div>
Writing Simple Dash app
我们将在文件 dashApp.py 中学习如何使用上述库编写一个简单的 Dash 示例。
We will learn how to write a simple example on dash using above mentioned library in a file 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)
Running the Dash app
在运行 Dash 应用程序时,请注意以下几点:
Note the following points while running the Dash app.
(MyDjangoEnv) C:\Users\rajesh\Desktop\MyDjango\dash>python dashApp1.py
-
Serving Flask app "dashApp1" (lazy loading)
-
Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead.
-
Debug mode: on
-
Restarting with stat
-
Debugger is active!
-
Debugger PIN: 130-303-947
-
Running on http://127.0.0.1:8050/ (Press CTRL+C to quit)
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 -
在您的网络浏览器中访问 http:127.0.0.1:8050/ 。您应该会看到一个类似于此的应用程序。
Visit http:127.0.0.1:8050/ in your web browser. You should see an app that looks like this.

在上述程序中,需要特别注意以下几点:
In above program, few important points to be noted are as follows −
-
The app layout is composed of a tree of “components” like html.Div and dcc.Graph.
-
The dash_html_components library has a component for every HTML tag. The html.H1 (children = ‘Hello Dash’) component generates a <h1> Hello Dash </h1> HTML element in your application.
-
Not all components are pure HTML. The dash_core_components describe higher-level components that are interactive and are generated with JavaScript, HTML, and CSS through the React.js library.
-
Each component is described entirely through keyword attributes. Dash is declarative: you will primarily describe your application through these attributes.
-
The children property is special. By convention, it’s always the first attribute which means that you can omit it.
-
Html.H1 (children=’Hello Dash’) is the same as html.H1 (‘Hello Dash’).
-
The fonts in your application will look a little bit different than what is displayed here. This application is using a custom CSS stylesheet to modify the default styles of the elements. Custom font style is permissible, but as of now, we can add the below URL or any URL of your choice − app.css.append_css ({“external_url”:*https://codepen.io/chriddyp/pen/bwLwgP.css*}) to get your file to get the same look and feel of these examples.
More about HTML
dash_html_compoments 库包含一个用于所有 HTML 标签的组件类,以及所有 HTML 参数的关键字参数。
The dash_html_components library contains a component class for every HTML tag as well as keyword arguments for all of the HTML arguments.
让我们在先前应用文本中添加组件的内联样式 -
Let us add the inline style of the components in our previous app text −
# -*- 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)
在上面的示例中,我们使用 style 属性修改了 html.Div 和 html.H1 组件的内联样式。
In the above example, we modified the inline styles of the html.Div and html.H1 components with the style property.

它在 Dash 应用程序中被渲染如下 -
It is rendered in the Dash application as follows −

dash_html_components 和 HTML 属性有一些关键区别 -
There are couple of key distinctions between dash_html_components and HTML attributes −
-
For style property in Dash, you can just supply a dictionary, whereas in HTML, it is semicolon-separated string.
-
Style dictionary keys are camelCased, so text-align changes to textalign.
-
ClassName in Dash is similar to HTML class attribute.
-
The first argument is the children of the HTML tag which is specified through the children keyword argument.
Reusable Components
通过用 Python 编写我们的标记,我们可以创建复杂的、可重用的组件(比如表格),而无需切换上下文或语言 -
By writing our markup in Python, we can create complex reusable components like tables without switching contexts or languages −
下面是一个快速示例,它从 pandas 数据框生成一个“表格”。
Below is a quick example that generates a “Table” from pandas dataframe.
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)
我们的输出将类似于 -
Our output will be something like −

More about Visualization
dash_core_components 库包含一个名为 Graph 的组件。
The dash_core_components library includes a component called Graph.
Graph 使用开源 plotly.js JavaScript 绘图库呈现交互式数据可视化。Plotly.js 支持约 35 种图表类型,并在矢量质量 SVG 和高性能 WebGL 中呈现图表。
Graph renders interactive data visualizations using the open source plotly.js JavaScript graphing library. Plotly.js support around 35 chart types and renders charts in both vector-quality SVG and high-performance WebGL.
下面是一个从 Pandas 数据框创建散点图的示例 -
Below is an example that creates a scatter plot from a Pandas dataframe −
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()
以上代码的输出如下所示 -
The output of the above code is as follows −

这些图形是交互式的和响应式的。你可以将鼠标悬停在点上以查看其值,单击图例项以切换迹线,单击并拖动进行缩放,按住 shift 并单击并拖动进行平移。
These graphs are interactive and responsive. You can hover over points to see their values, click on legend items to toggle traces, click and drag to zoom, hold down shift, and click and drag to pan.
Markdown
当 dash 通过 dash_html_components 库展现 HTML 风格时,用 HTML 编写副本可能很乏味。对于书写文本块,你可以在 dash_core_components 库中使用 Markdown 组件。
While dash exposes HTML flavours through the dash_html_components library, it can be tedious to write your copy in HTML. For writing blocks of texts, you can use the Markdown component in the dash_core_components library.
Core Components
dash_core_components 包含一组更高级别的组件,如下拉菜单、图形、markdown、块等等。
The dash_core_components includes a set of higher-level components like dropdowns, graphs, markdown, blocks and many more.
与其他所有 Dash 组件一样,它们是完全声明式描述的。每个可配置选项都作为组件的关键字参数提供。
Like all other Dash components, they are described entirely declaratively. Every option that is configurable is available as a keyword argument of the component.
下面是这个示例,用到了一些可用的组件−
Below is the example, using some of the available components −
# -*- 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)
以上程序的输出如下−
Output from the above program is as follows −

Calling Help
Dash 组件是声明式的。在安装时,这些组件的每一个可配置方面均作为关键字参数设置。你可以在你的 Python 控制台中,在组件上调用帮助来学习更多关于一个组件和它的可用参数的信息。其中一些信息如下−
Dash components are declarative. Every configurable aspect of these components is set during installation as a keyword argument. You can call help in your python console on any of the components to learn more about a component and its available arguments. Some of them are given below −
>>> 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 标签和关键字参数提供了类,描述了 HTML 属性,如样式、类名和 id。dash_core_components 库生成了高级组件,如控件和图表。
To summarize, the layout of a Dash app describes what the app looks like. The layout is a hierarchical tree of components. The dash_html_components library provides classes for all the HTML tags and the keyword arguments, and describes the HTML attributes like style, className, and id. The dash_core_components library generates higher-level components like controls and graphs.