(data science learning notes 104) Python + dash rapid web application development -- callback interaction (Part 1)

Fevrey 2021-01-22 20:05:18
data science learning notes 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 third issue of , In the first two tutorials , We focus on what is Dash, And how to cooperate with the convenient third-party development dash-bootstrap-components For our Dash The application design layout is introduced in great detail .

and Dash What attracts me most is that it is highly encapsulated react.js, So that we don't have to write js sentence , pure Python Programming can realize the normal asynchronous communication between the browser front-end and back-end computing , To create a powerful interactive web application .

chart 1

Starting with today's article , I'm going to start taking you into Dash The core content —— Callback .

2 Dash The basic callback in

2.1 The most basic callback

Dash Medium Callback callback) In the form of ornaments , With self-made callback function , Realize asynchronous communication between front end and back end , This sentence may not be easy to understand , Let's start with a simple example Dash Medium Callback

app1.py

import dash
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output
app = dash.Dash(
__name__,
external_stylesheets=['css/bootstrap.min.css']
)
app.layout = html.Div(
[
html.Br(),
html.Br(),
html.Br(),
dbc.Container(
[
dbc.Row(
[
dbc.Col(dbc.Input(id='input-value',
placeholder=' Please input something '),
width=12),
dbc.Col(dbc.Label(id='output-value'),
width=12)
]
)
]
)
]
)
# Corresponding app Instance of the callback function decorator
@app.callback(
Output('output-value', 'children'),
Input('input-value', 'value')
)
def input_to_output(input_value):
'''
Simple callback functions
'''
return input_value
if __name__ == '__main__':
app.run_server()

First look at it. app1 The interaction effect of :

chart 2

Let's break down the above code , Let's sort out how to construct a system with actual interaction function Dash What applications need to do :

  • Identify input and output components

An interactive system must have Input And Output Of , We started with Input And Output object , They play, respectively Input by And Exporter Two characters , Their respective first parameter component_id It is used to link the components defined in the front part .

When we defined front-end components earlier , by dbc.Input The corresponding input box is set with id='input-value', by dbc.Label The corresponding text output setting is id='output-value', Let them be the first parameter that can be Input() And Output() Unique identification .

  • Determine the input and output

It's time to make sure Input by And Exporter after , More importantly, to tell Dash What input needs to be monitored , In response to what output , This is going to take the second parameter component_property.

It's related to the corresponding front end components , For example, our dbc.Input() Input box , All the input contents exist value Properties of the , and children The attribute is dbc.Label And the vast majority html The first parameter of the part , So we've identified the input and output .

  • Decorate the callback function

app.callback() The decorator is in accordance with the regulations Output() after Input() Pass in the corresponding objects in the same order , And since it's a decorator , Naturally, it needs to be used with a custom callback function .

our input_to_output() It's the corresponding callback function , Its parameters are the same as that of the decorator Input() Corresponding , The function interior is used to define the calculation process .

Last return The object corresponding to Output().

# Corresponding app Instance of the callback function decorator
@app.callback(
Output('output-value', 'children'),
Input('input-value', 'value')
)
def input_to_output(input_value):
'''
Simple callback functions
'''
return input_value

Through the structure above , We have to be pure Python“ A few words ” Realized the interactive function , Give us the ability to write anything Dash Ability to apply .

2.2 Set up multiple Input() And Output()

In the last section, we introduced the most basic Single input -> Single output Callback mode , A lot of times we need more complex callback patterns , For example, the following example :

app2.py

import dash
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output
app = dash.Dash(
__name__,
external_stylesheets=['css/bootstrap.min.css']
)
app.layout = html.Div(
[
html.Br(),
html.Br(),
html.Br(),
dbc.Container(
[
dbc.Row(
[
dbc.Col(dbc.Input(id='input-value1'), width=3),
dbc.Col(html.P('+'), width=1),
dbc.Col(dbc.Input(id='input-value2'), width=3),
],
justify='start'
),
html.Hr(),
dbc.Label(id='output-value')
]
)
]
)
@app.callback(
Output('output-value', 'children'),
Input('input-value1', 'value'),
Input('input-value2', 'value')
)
def input_to_output(input_value1, input_value2):
try:
return float(input_value1) + float(input_value2)
except:
return ' Please enter legal parameters !'
if __name__ == '__main__':
app.run_server()
chart 3

Here our Input() There's more than one object , stay Output() Object and then pass in ( You can also put all Input() Object packages are passed in in a list ), The order corresponds to the parameter order of the following callback function , So as to realize the one-to-one correspondence of multiple input values .

alike ,Output() There can be more than one :

app3.py

import dash
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output
app = dash.Dash(
__name__,
external_stylesheets=['css/bootstrap.min.css']
)
app.layout = html.Div(
[
html.Br(),
html.Br(),
html.Br(),
dbc.Container(
[
dbc.Row(
[
dbc.Col(dbc.Input(id='input-lastname'), width=3),
dbc.Col(html.P('+'), width=1),
dbc.Col(dbc.Input(id='input-firstname'), width=3),
],
justify='start'
),
html.Hr(),
dbc.Label(id='output1'),
html.Br(),
dbc.Label(id='output2')
]
)
]
)
@app.callback(
[Output('output1', 'children'),
Output('output2', 'children')],
[Input('input-lastname', 'value'),
Input('input-firstname', 'value')]
)
def input_to_output(lastname, firstname):
try:
return ' Full name :' + lastname + firstname, f' The length of the name is {len(lastname+firstname)}'
except:
return ' Waiting for input ...', ' Waiting for input ...'
if __name__ == '__main__':
app.run_server()
chart 4

You can see that no matter how many Output() still Input(), Just nest it in the list .

2.3 utilize State() Achieve lazy interaction

In many cases , If our callback function is time consuming , Well, as I mentioned earlier, it's just Input() And Output() The communication between the front end and the back end will be very frequent , Because the corresponding property values of all the input components monitored only need to change a little , It will trigger a callback .

To solve this kind of problem ,Dash Designed in State() object , We can use State() Replace Input() To bind the corresponding input value , And then we'll take some things that need to be triggered actively, such as dbc.Button() Properties of button parts n_clicks, As Input() Object to bind .

Let's better understand its function through the following examples :

app4.py

import dash
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State
app = dash.Dash(
__name__,
external_stylesheets=['css/bootstrap.min.css']
)
app.layout = html.Div(
[
html.Br(),
html.Br(),
html.Br(),
dbc.Container(
[
dbc.Row(
[
dbc.Col(dbc.Input(id='input-value'),
width=4),
dbc.Col(dbc.Button(' Small to capital ',
id='state-button',
n_clicks=0),
width=4),
dbc.Col(dbc.Label(id='output-value',
style={'padding': '0',
'margin': '0',
'line-height': '38px'}),
width=4)
],
justify='start'
)
]
)
]
)
@app.callback(
Output('output-value', 'children'),
Input('state-button', 'n_clicks'),
State('input-value', 'value')
)
def input_to_output(n_clicks, value):
if n_clicks:
return value.upper()
if __name__ == '__main__':
app.run_server()
chart 5

You can see , In the decorator, according to Output()Input()State() After passing in the order of each object , our Button() Of components n_clicks The parameter records how many times the corresponding button has been clicked , Initialization we set it to 0, After that, every time we input the words , When you click a button to increase the number of clicks , The callback function will be triggered , This facilitates many of our complex application scenarios ~


That's all for this issue , Welcome to discuss with me in the comments section ~

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

  1. python中hmac模块的使用
  2. Python crawler_ Garbage man idle fish crawler turn crawler data integration self use second hand rapid response garbage collection platform_ 3 (with continuous source update)
  3. Using Python javaserialization tools module to generate 8u20 gadget
  4. The basic syntax of Python
  5. The use of HMAC module in Python
  6. 攻防世界web进阶区Web_python_block_chain详解
  7. Attack and defense world web advanced zone Web_ python_ block_ Details of chain
  8. pandas DataFrame的新增行列,修改、删除、筛选、判断元素以及转置操作
  9. Add rows and columns, modify, delete, filter, judge elements and transpose operations in pandas dataframe
  10. pandas DataFrame的新增行列,修改、删除、筛选、判断元素以及转置操作
  11. Add rows and columns, modify, delete, filter, judge elements and transpose operations in pandas dataframe
  12. 虚言妙诀终虚见,面试躬行是致知,Python技术面试策略与技巧实战记录
  13. The interview practice is knowledge, python technology interview strategy and skills of the actual record
  14. 用tqdm和rich为固定路径和目标的python算法代码实现进度条
  15. Using tqdm and rich as the fixed path and target of Python algorithm code to realize the progress bar
  16. 我来记笔记啦-Django开发流程与配置
  17. Let me take notes - Django development process and configuration
  18. python数据类型的强制转换
  19. Django报错:'Key 'id' not found in 'xxx'. Choices are: xxx'
  20. Python400集大型视频,从正确的方向出发学习,全套完整送给大家
  21. Mandatory conversion of Python data type
  22. Django reported an error: 'key' ID 'not found in' xxx '. Choices are: xxx'
  23. Python 400 sets of large video, starting from the right direction to learn, a complete set to you
  24. 只需十四步:从零开始掌握Python机器学习(附资源)
  25. Just 14 steps: Master Python machine learning from scratch (resources attached)
  26. Python|文件读写
  27. 安利一个Python界神奇得网站
  28. Python | file reading and writing
  29. Amway is a marvelous website in Python world
  30. 第二热门语言:从入门到精通,Python数据科学简洁教程
  31. The second popular language: from introduction to mastery, python data science concise tutorial
  32. 以我的亲身经历,聊聊学python的流程,同时推荐学python的书
  33. With my own experience, I'd like to talk about the process of learning Python and recommend books for learning python
  34. 以我的亲身经历,聊聊学python的流程,同时推荐学python的书
  35. With my own experience, I'd like to talk about the process of learning Python and recommend books for learning python
  36. Django url 路由匹配过程
  37. Django URL routing matching process
  38. 强者一出,谁与争锋?与Python相比,C++的运行速度究竟有多快?
  39. Who will fight against the strong? How fast is C + + running compared with Python?
  40. python 学习体会
  41. Experience of learning Python
  42. python7、8章
  43. Chapter 7 and 8 of Python
  44. python bool和str转换
  45. python——循环(for循环、while循环)及练习
  46. python变量和常量命名、注释规范
  47. python自定义异常捕获异常处理异常
  48. python 类型转换与数值操作
  49. python 元组(tuple)和列表(list)区别
  50. 解决python tkinter 与 sleep 延迟问题
  51. python字符串截取操作
  52. Python bool and STR conversion
  53. Python -- loop (for loop, while loop) and Practice
  54. Specification for naming and annotating variables and constants in Python
  55. Python custom exception capture exception handling exception
  56. Python type conversion and numerical operation
  57. The difference between tuple and list in Python
  58. Solve the delay problem of Python Tkinter and sleep
  59. Python string interception operation
  60. Python 100天速成中文教程,GitHub标星7700