(learning notes of data science 108) Python + dash rapid web application development -- static components (I)

Fevrey 2021-02-20 19:15:52
learning notes data science python


The sample code for this article has been uploaded to my Github Warehouse https://github.com/CNFeffery/DataScienceStudyNotes

1 brief introduction

This is my series of tutorials Python+Dash Fast web application development The sixth issue of , In the last article , We're done. Yeah Dash Discussion on the advanced features of callback interaction in , In the course content that will be released one after another in the future , We will study together Dash Those rich in Ecology Page parts , So that we can create all kinds of powerful interactive web Ability to apply .

And in today's tutorial , I will take you to learn Dash Some basic practical Static components , They can help us build more formal web application .

chart 1

2 Dash The basic static components in

What we call static page parts here , Mainly refers to its own does not have direct interactive function , But rather Present content For the main function , Just like the simple comparison below :

app1.py

import dash
import dash_html_components as html
import dash_bootstrap_components as dbc
import dash_core_components as dcc
app = dash.Dash(__name__)
app.layout = html.Div(
dbc.Container(
[
html.Br(),
html.H1(' Examples of static components '),
html.Hr(),
html.H2(' This is the secondary title '),
html.H3(' This is a three-level title '),
html.H4(' This is the fourth level title '),
html.P(
[
' This is a ',
html.A(' link ', href='#'),
', And this is a period of ',
html.Strong(' Bold text '),
', This is a text with a superscript and a subscript :',
' test ',
html.Sup(' Superscript '),
', test ',
html.Sub(' Subscript ')
]
),
html.Br(),
html.H1(' Examples of interactive components '),
html.Br(),
dcc.Dropdown(
options=[
{'label': ' test 1', 'value': ' test 1'},
{'label': ' test 2', 'value': ' test 2'},
{'label': ' test 3', 'value': ' test 3'},
]),
html.Br(),
dcc.Checklist(
options=[
{'label': ' test 1', 'value': ' test 1'},
{'label': ' test 2', 'value': ' test 2'},
{'label': ' test 3', 'value': ' test 3'},
],
value=[' test 1']
),
html.Br(),
dcc.RangeSlider(
min=0,
max=20,
step=0.5,
value=[5, 15]
)
]
)
)
if __name__ == '__main__':
app.run_server(debug=True)
chart 2

You can see , In fact, static components are all kinds of content elements that we usually see when browsing web pages , They are not directly responsible for the callback interaction function , It can only cooperate with other interactive components to achieve interactive functions .

2.1 Dash The basic static components commonly used in engineering

stay Dash Some common basic static components integrated in , In fact, it's about some common html The migration of elements , Corresponding dash_html_components Many classes encapsulated in , Here we only introduce some common :

First of all, let's introduce Dash Among many basic static components , Some related to organizing pages or text formats :

  • H1() To H6()

stay dash_html_components in ,H1() To H6() Corresponding to 1 Class to 6 Level title .

  • Br() And Hr()

dash_html_components Medium Br() Means line break , and Hr() It means the horizontal dividing line , This is often used when we layout elements .

  • P()

P() Used to represent a piece of text or content , Typically, as we see in the blog, every paragraph is made up of P() What LABELS Organize , coordination css Medium text-indent Property can be used to set the first line indent .

  • A()

A() Used to represent a clickable link , Its parameters href Used to fill in the address of the corresponding jump , Can also cooperate id, Click to relocate to other elements in the page , Its target Parameter is used to set the jump mode , for example target="_blank" Will jump to open on the new tab , Please refer to (https://www.w3school.com.cn/tags/att_a_target.asp).

  • I()、Code()、U()、Mark()

I() It is mainly used to change the text content of the package into Italics ,Code() Used to express in a paragraph code snippet ,U() Used to underline what is included ,Mark() Is used to highlight dimension text .

The static components described above can be intuitively felt through the following small examples :

app2.py

import dash
import dash_html_components as html
import dash_bootstrap_components as dbc
app = dash.Dash(__name__)
app.layout = html.Div(
dbc.Container(
[
html.H1(' First level title ', id='demo1'),
html.H2(' Secondary title '),
html.H3(' Three level title '),
html.H4(' The fourth level title '),
html.H5(' Five level titles '),
html.H6(' Six level title '),
html.Br(), # Line break
html.Hr(), # Horizontal split line
html.P(' This is a passage .'*20),
html.P(' This is another piece of text with the first line indented .'*10, style={'text-indent': '3rem'}),
html.A(' Jump to fevrey's Github Warehouse ',
target='_blank',
href='https://github.com/CNFeffery/DataScienceStudyNotes'), # Jump to external links
html.Br(),
html.A(' Jump to level 6 title ', href='#demo2'),
html.P(
[
' There's something in a passage ',
html.I(' Italics '),
', And code snippets ',
html.Code('import dash'),
', There's another paragraph ',
html.U(' Underlined text '),
', a section ',
html.Mark(' Highlight the text '),
', And another paragraph ',
html.Mark(' Highlight text in different colors .', style={'background-color': 'lightblue'})
]
)
] + [html.Br()] * 50 + [html.A(' Back to the top level title ', href='#demo1'),
html.H1(' In page elements jump to sample title ', id='demo2')]
)
)
if __name__ == '__main__':
app.run_server(debug=True)
chart 3

Previously, we introduced some common static components related to text format , In practical application, we should not only show the text content , You also need to show pictures 、 Audio 、 Video and other multimedia content , Now let's learn how to Dash More abundant content presentation forms are constructed in :

  • be based on Blockquote() Implement block references

utilize dash_html_components Medium Blockquote(), We can pass in a string directly , Or nesting other elements , So we can construct a block reference , It's like markdown Medium > The content contained in the rendering is like , Refer to the following example :

app3.py

import dash
import dash_html_components as html
import dash_bootstrap_components as dbc
app = dash.Dash(__name__)
app.layout = html.Div(
dbc.Container(
html.Blockquote(
html.P(' This is a piece of text wrapped by a block reference ' * 10),
style={
'background-color': 'rgba(211, 211, 211, 0.25)',
'text-indent': '3rem'
}
)
)
)
if __name__ == "__main__":
app.run_server(debug=True)
chart 4
  • be based on Ol() And Li() Rendering has a sequence table

utilize Ol() Nesting multiple Li(), You can automatically render an ordered list with serial numbers , Like this simple example :

app4.py

import dash
import dash_html_components as html
import dash_bootstrap_components as dbc
app = dash.Dash(__name__)
app.layout = html.Div(
dbc.Container(
html.Ol(
[
html.Br(),
html.Br(),
html.Li(' To do list 1'),
html.Li(' To do list 2'),
html.Li(' To do list 3'),
html.Li(' To do list 4')
]
)
)
)
if __name__ == "__main__":
app.run_server(debug=True)
chart 5
  • be based on Ul() And Li() List of render levels

And in addition to Ol() In addition to mutual cooperation ,Li() It can also be nested in Ul() Render a hierarchical list in :

app5.py

import dash
import dash_html_components as html
import dash_bootstrap_components as dbc
app = dash.Dash(__name__)
app.layout = html.Div(
dbc.Container(
html.Ul(
[
html.Br(),
html.Br(),
html.Li('1'),
html.Li('2'),
html.Ul(
[
html.Li('2.1'),
html.Li('2.2'),
html.Li('2.3'),
html.Ul(
[
html.Li('2.1.1'),
html.Li('2.1.2'),
html.Li('2.1.3'),
]
)
]
),
html.Li('3'),
html.Li('4')
]
)
)
)
if __name__ == "__main__":
app.run_server(debug=True)
chart 6
  • utilize Img() Rendering pictures

Img() Equivalent to html Medium img label , We go through src The parameter passes in the picture address to render the picture , Take the picture of my previous blog as an example :

app6.py

import dash
import dash_html_components as html
import dash_bootstrap_components as dbc
app = dash.Dash(__name__)
app.layout = html.Div(
dbc.Container(
[
html.H5('( Refine data visualization in simulation 05) Market value growth during the epidemic top25 company '),
html.Img(src='https://img2020.cnblogs.com/blog/1344061/202011/1344061-20201129183046286-1089258422.png',
style={'width': '100%'})
]
)
)
if __name__ == "__main__":
app.run_server(debug=True)
chart 7
  • utilize Audio() And Video() Play audio and video

utilize Audio() and Video(), We can go through the parameters src Pass in the corresponding audio and video files url Address , So that we can embed audio and video in the web page , The parameter controls Must be set to True Otherwise it won't render properly :

app7.py

import dash
import dash_html_components as html
import dash_bootstrap_components as dbc
app = dash.Dash(__name__)
app.layout = html.Div(
dbc.Container(
[
html.H5(' Audio sample :'),
html.Audio(src='https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3',
controls=True),
html.H5(' Video examples :'),
html.Video(src='https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4',
controls=True,
style={'width': '100%'}),
]
)
)
if __name__ == "__main__":
app.run_server(debug=True)
chart 8
  • utilize Iframe() Embed other pages

similar iframe label , We can also use it Iframe() To embed other pages in a web page , Can pass src Parameters are passed directly into the target web page url, It can also be done through srcDoc Parameters are passed into the html Source string :

app8.py

import dash
import dash_html_components as html
import dash_bootstrap_components as dbc
app = dash.Dash(__name__)
app.layout = html.Div(
dbc.Container(
[
html.Iframe(src='https://www.baidu.com/',
style={'width': '100%', 'height': '800px'})
]
)
)
if __name__ == "__main__":
app.run_server(debug=True)
chart 9
  • utilize Textarea() Construct input fields

Sometimes we need to construct an input box for users to input large pieces of text , For example, a lot of online editors , And in the Dash We can use dash_core_components Medium Textarea() To achieve this function , also dcc.Textarea() Also has value and placeholder attribute , It can cooperate with callback function to realize many functions .

For example, in the following example, we have written a simple tool for swearing harmony , All the information entered by the user will be Fucking Replace with “**”:

app9.py

import dash
import dash_html_components as html
import dash_bootstrap_components as dbc
import dash_core_components as dcc
from dash.dependencies import Input, Output
app = dash.Dash(__name__)
app.layout = html.Div(
dbc.Container(
[
html.Br(),
dcc.Textarea(style={'width': '100%', 'height': '300px'},
id='input',
value='',
placeholder=' Please enter the text !'),
html.P(id='output')
]
)
)
@app.callback(
Output('output', 'children'),
Input('input', 'value')
)
def mask_dirty_talk(value):
return value.replace(' Fucking ', '**')
if __name__ == "__main__":
app.run_server(debug=True)
chart 10

2.2 dcc.Markdown()——Dash A special static component in the

stay Dash There is also a special component for rendering static content ——dcc.Markdown(), its children Parameter acceptance markdown Code , And automatically present the rendered effect in the web page , The main parameters are as follows :

children: Character markdown Source code

dangerously_allow_html:bool type , Used to set whether parsing is allowed markdown In the source html Code and render , The default is False That is, no rendering

dedent:bool type , Code used to set whether to ignore the beginning of each line of text , The default is True

The effect is as follows :

app10.py

import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
app = dash.Dash(__name__)
app.layout = html.Div(
dbc.Container(
[
dcc.Markdown('''
> The sample code for this article has been uploaded to my `Github` Warehouse [https://github.com/CNFeffery/DataScienceStudyNotes](https://github.com/CNFeffery/DataScienceStudyNotes)
# 1 brief introduction
This is my series of tutorials **Python+Dash Fast web application development ** The fifth issue of , In the last article , We aim at `Dash` Some technical features of callbacks are introduced in , So that we can be more happy for `Dash` Application writing callback interaction function .
And today's article serves as ** Callback interaction ** The last issue of systematic content , I'm going to take you get some `Dash` The practical application effect is amazing ** Advanced callback features **, Buckle up , We take off ~
<p align="center"><img src="https://img2020.cnblogs.com/blog/1344061/202102/1344061-20210207194037614-808613819.png" style="zoom:100%;" /></p>
''',
dangerously_allow_html=True,
dedent=False)
]
)
)
if __name__ == "__main__":
app.run_server(debug=True)
chart 11

With Markdown() The blessing of parts , We can use it directly in some cases markdown Write web pages quickly , For example, writing an online document description page ~

3 utilize Dash Homemade online Markdown Editor

After mastering the knowledge involved in today's tutorial , We can write some interfaces with practical interaction functions by ourselves , For example, make an online Markdown Editor .

The idea is simple , Use what you've learned today Textarea() Of components value Property as a callback Input(), then Markdown() Of components children Element as a callback Output(), A little more beautification of the layout , The following effects are achieved ~

chart 12

The corresponding code is as follows :

app11.py

import dash
import dash_html_components as html
import dash_core_components as dcc
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output
app = dash.Dash(__name__)
app.layout = html.Div(
dbc.Container(
dbc.Row(
[
dbc.Col(
dcc.Textarea(
id='md-input',
placeholder=' Please enter your markdown Source code !',
style={
'width': '100%',
'height': '100%'
}
),
width=6,
style={
'padding-right': 0,
'border': 'border:5px solid red'
}
),
dbc.Col(
dcc.Markdown(id='md-output',
dangerously_allow_html=True,
style={
'position': 'absolute',
'width': '100%',
'height': '100%'
}),
width=6,
style={
'position': 'relative',
'overflow': 'auto',
'padding-left': 0
}
),
],
style={
'position': 'fixed',
'top': 0,
'bottom': 0,
'left': 0,
'right': 0
}
)
),
style={
'font-size': '2rem'
}
)
@app.callback(
Output('md-output', 'children'),
Input('md-input', 'value')
)
def online_markdown(raw_text):
return raw_text
if __name__ == '__main__':
app.run_server(debug=True)

The above is the whole content of this paper , We'll continue to explore in the next tutorial Dash Static components that are easier to use and more functional in , Coming soon ~

The above is the whole content of this paper , Welcome to discuss with me in the comments section .

版权声明
本文为[Fevrey]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/02/20210220191457994e.html

  1. Python pandas: using pandas to add row data, that is, adding dictionary data to dataframe according to row data cycle
  2. Python:将Flask测试应用部署到Deta
  3. Python:OAuth2第三方登录之Github
  4. Python:使用pydantic库进行数据校验
  5. Python:免费IP归属地查询接口
  6. Python:使用user-agents库解析浏览器信息
  7. Python:cached_property缓存对象的属性
  8. Python:打包配置文件 setup.py 详解
  9. Python:ORM(Object Relational Mapper)模块汇总整理
  10. Python:datetime时间UTC时间转东八区
  11. Python: deploying flash test application to deta
  12. Python: oauth2 GitHub for third party login
  13. Python: using pydantic library for data verification
  14. Python: free IP home location query interface
  15. Python: parsing browser information using user agents Library
  16. Python:cached_ Property to cache the properties of an object
  17. Python: packaging configuration files setup.py Detailed explanation
  18. Python: ORM (object relational mapper) module summary
  19. Python: datetime, UTC, turn to District 8, East
  20. python tkinter 将某一目录下的所有图片插入到docx文件中
  21. Python Tkinter inserts all the pictures in a directory into the docx file
  22. 解决忽略VScode中Python插件pylint报错的问题
  23. To solve the problem of ignoring the error of Python plug-in in vscode
  24. python 毫秒级时间,时间戳转换
  25. Python millisecond time, timestamp conversion
  26. python try except 出现异常时,except 中如何返回异常的信息字符串
  27. When an exception occurs in Python try except, how to return the exception information string in except
  28. 手机最强Python编程神器,在手机上运行Python
  29. The strongest Python Programming artifact on mobile phones, running Python on mobile phones
  30. 2021年Python程序员薪资待遇如何?
  31. 「python安装」Windows上安装和创建python开发环境
  32. What is the salary of Python programmers in 2021?
  33. "Python installation" to install and create a python development environment on Windows
  34. python解决组合问题
  35. Python to solve the problem of composition
  36. Python中的Lasso回归之最小角算法LARS
  37. Lars, the least angle algorithm of lasso regression in Python
  38. 利用python提取网站曲线图数据
  39. Using Python to extract website graph data
  40. Python3中urllib详细使用方法(header,代理,超时,认证,异常处理)
  41. Detailed usage of urllib in Python 3 (header, proxy, timeout, authentication, exception handling)
  42. python 第三方库paramiko
  43. python 第三方库paramiko
  44. Python third party library paramiko
  45. Python third party library paramiko
  46. 卸载 PyCharm!这才是 Python 小白的最理想的 IDE
  47. 卸载 PyCharm!这才是 Python 小白的最理想的 IDE
  48. Uninstall pycharm! This is the ideal IDE for Python Xiaobai
  49. django学习-27.admin管理后台里:对列表展示页面的数据展示进行相关优化
  50. Uninstall pycharm! This is the ideal IDE for Python Xiaobai
  51. Django learning - 27. Admin management background: optimize the data display of the list display page
  52. python day2
  53. python day2
  54. Python 内存泄漏问题排查
  55. Troubleshooting of Python memory leak
  56. Python 与 excel的简单应用
  57. Simple application of Python and excel
  58. Python 与 excel的简单应用
  59. Simple application of Python and excel
  60. 2.7万 Star!最全面的 Python 设计模式集合