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

itread01 2021-01-22 21:21:13
materials science learning notes python


> The sample code for this article has been uploaded to my `Github` Warehouse [https://github.com/CNFeffery/DataScienceStudyNotes](https://github.com/CNFeffery/DataScienceStudyNotes)# 1 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` Come for us `Dash` The application design layout is introduced in great detail . and `Dash` What attracts me most is its high encapsulation `react.js`, So that we don't have to write `js` Sentence , Pure `Python` The program design can realize the normal asynchronous communication between the front end and the back end of the browser , So as to create a powerful interactive `web` Apply . Starting with today's article , I'm going to start taking you into `Dash` The core content of ——** Call back **.# 2 Dash Basic callback in ## 2.1 The most basic call back `Dash` Medium ** Call back **(*callback*) In the form of ornaments , With the self-made callback function , Realize the front and back end asynchronous communication interaction , This sentence may not be easy to understand , Let's start with a simple example `Dash` Medium ** Call back **:> app1.py```Pythonimport dashimport dash_html_components as htmlimport dash_bootstrap_components as dbcfrom dash.dependencies import Input, Outputapp = 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) ] ) ] ) ])# Correspondence app The callback function decorator for example @app.callback( Output('output-value', 'children'), Input('input-value', 'value'))def input_to_output(input_value): ''' A simple callback function ''' return input_valueif __name__ == '__main__': app.run_server()``` Let's see first `app1` The interactive effect of : Let's break down the code above , Let's sort out how to construct a system with practical interactive 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` thing , They play respectively ** Input by ** And ** Exporter ** Two characters , Their respective first arguments `component_id` It is used to link the components defined in the front end part . When we defined front-end components earlier , For `dbc.Input` The corresponding input box is set to `id='input-value'`, For `dbc.Label` The corresponding text output is set to `id='output-value'`, Let them be used as the first argument to be `Input()` And `Output()` The only way to identify .- ** Determine the input and output ** It's time to make sure ** Input by ** And ** Exporter ** After that , More importantly, to tell `Dash` What input needs to be monitored , Respond to what output , That's the second argument `component_property`. It is related to the corresponding front-end components , For example, our `dbc.Input()` Input box , All the input contents exist `value` Attribute , and `children` Property is `dbc.Label` And the vast majority of `html` The first argument to 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()` The corresponding objects are passed in the order of , And since it's a decorator , Naturally, it needs to be used with a custom callback function . Our `input_to_output()` The corresponding callback function , Its argument is the same as that in the decorator `Input()` Correspondence , The inner part of the function is used to define the calculation process . Finally `return` And the objects corresponding to `Output()`.```Python# Correspondence app The callback function decorator for example @app.callback( Output('output-value', 'children'), Input('input-value', 'value'))def input_to_output(input_value): ''' A simple callback function ''' return input_value``` Through the structure above , We have to be pure `Python`“ A few words ” The interactive function is realized , Give us the ability to write anything `Dash` The ability to apply .## 2.2 Set multiple at the same time Input() And Output() In the last section, we introduced the most basic ** Single input -> Single output ** Call back mode , A lot of times we need a more complex callback mode , For example, the following example :> app2.py```Pythonimport dashimport dash_html_components as htmlimport dash_bootstrap_components as dbcfrom dash.dependencies import Input, Outputapp = 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 a legal argument !'if __name__ == '__main__': app.run_server()``` Here's our `Input()` There is more than one object , stay `Output()` Objects are then passed in in turn ( You can also put all `Input()` The package is passed in a list ), The order corresponds to the argument order of the following callback function , So as to realize the one-to-one correspondence of multiple input values . The same ,`Output()` There can be more than one :> app3.py```Pythonimport dashimport dash_html_components as htmlimport dash_bootstrap_components as dbcfrom dash.dependencies import Input, Outputapp = 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()``` You can see that no matter how many `Output()` Or `Input()`, Just nest in the list .## 2.3 utilize State() Achieve inert interaction In many cases , If the computation time of our callback function is large , So just like what I've just introduced `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 , A callback will be triggered . In order to solve such problems ,`Dash` In the design of `State()` thing , We can use `State()` Replacement `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()` Objects . Let's better understand its function through the following examples :> app4.py```Pythonimport dashimport dash_html_components as htmlimport dash_bootstrap_components as dbcfrom dash.dependencies import Input, Output, Stateapp = 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(' Lower case to upper case ', 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()``` 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 argument records how many times the corresponding button has been selected , We set it to 0, After that, every time we input the words , When you actively click the button to increase the number of times it is selected , The callback function is triggered , This facilitates many of our complex application scenarios ~--- That's all for this issue , Welcome to join me in the comments section
版权声明
本文为[itread01]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/01/20210122211953196f.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