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 ~

( Data science learning notes 104)Python+Dash Fast web application development —— Callback interaction ( On ) More articles about

  1. ( Data science learning notes 75) be based on geopandas Spatial data analysis based on —— Coordinate reference system

    The corresponding code of this article has been uploaded to my Github Warehouse https://github.com/CNFeffery/DataScienceStudyNotes 1 brief introduction In the last article, we discussed geopandas Data nodes in ...

  2. ( Data science learning notes 84) be based on geopandas Spatial data analysis based on —— Space computing ( On )

    Sample code of this article . Data and files have been uploaded to my Github Warehouse https://github.com/CNFeffery/DataScienceStudyNotes 1 brief introduction In previous articles in this series, we focused on g ...

  3. ( Data science learning notes 88) be based on geopandas Spatial data analysis based on —— Space computing ( Next )

    The sample code and data of this article have been uploaded to my Github Warehouse https://github.com/CNFeffery/DataScienceStudyNotes 1 brief introduction Based on geopandas Series of spatial data analysis ...

  4. ( Data science learning notes 50) be based on Python Network data collection -selenium piece ( On )

    One . brief introduction And then a few months ago ( Data science learning notes 31) be based on Python Network data collection ( Elementary chapter ), In that article , We introduced the basics of web crawlers ( Basic request Library , Basic parsing library ,CSS, Regular expressions, etc ), In that article ...

  5. ( Data science learning notes 47) be based on Python The actual combat of network data collection (2)

    One . brief introduction I'm in my senior year , Recently in the summer internship , Outside the main business of data mining , Also help colleagues do a lot of network data collection content , The next few articles will be listed one by one , To continue to write a few months ago to open this network data collection practical pit . Two . Ma beehive reviews data collection ...

  6. ( Data science learning notes 32)Python in re Detailed introduction of the module

    One . brief introduction On regular expressions , I was in the previous article ( Data science learning notes 31) It has been introduced in detail in , This article will Python It comes with a module re Summarize the common functions of : re As Python It is a module specially designed for regular expression related functions , Provide ...

  7. ( Data science learning notes 80) use Python Write a small tool to download OSM Road network data

    The corresponding script of this article has been uploaded to my Github Warehouse https://github.com/CNFeffery/DataScienceStudyNotes 1 brief introduction In the process of data visualization or spatial data analysis, we often ...

  8. ( Data science learning notes 90)Python+Kepler.gl Make time carousels easily

    The sample code and data of this article have been uploaded to my Github Warehouse https://github.com/CNFeffery/DataScienceStudyNotes 1 brief introduction Kepler.gl As a powerful open source GIS ...

  9. ( Data science learning notes 55) utilize ggthemr To beautify ggplot2 Images

    One . brief introduction R Medium ggplot2 It's a very powerful and flexible data visualization package , Familiar with its drawing rules, you can freely generate various visual images , But its default color and style are unavoidably too simple in many cases , This article will introduce the ggthemr The package is specifically for the original ...

  10. ( Data science learning notes 49)Scala Pattern matching in

    One . brief introduction Scala Pattern matching in is similar to Java Medium switch sentence , And more robust , This article will focus on Scala Some basic examples of pattern matching are introduced : Two .Scala Pattern matching in 2.1 The basic format Scala Medium mode match ...

Random recommendation

  1. java4

    1: How to make help documents ( understand ) (1) Write a class (2) Add document comments (3) adopt javadoc Just generate the tool javadoc -d Catalog -author -version ArrayTool.java 2: ...

  2. About WPF How to browse the folder dialog box in

    When browsing the folder dialogresult To write a full reference path string path=null; FolderBrowserDialog fbd = new FolderBrowserDialog(); fbd ...

  3. Dynamic programming - Longest common subsequence (LCS)

    The longest common subsequence is also a classical problem in dynamic programming . There are two strings S1 and S2, Find the longest common substring , That is to find the string S3, It's also for S1 and S2 The string of , And it needs to be the longest , And determine the length . This is what we call ...

  4. WP8.1: About screen size and resolution

    Currently on the market Windows Phone More and more equipment , Size and resolution are also increasing , especially WP8.1 Coming of age . done wp Developers know that application adaptation is much simpler than Android , There is an important reason , It's Microsoft that claims to have WP set up ...

  5. Mac OS X 10.10 Yosemite Lower installation java、jdk、mysql、maven、idea

    Mac OS X Yosemite Already in 2014 year 10 month 17 It's officially released on . As a java developer , Try to install the latest version for the first time . And before OS X There are still many different systems . The following is mainly about java Development environment ...

  6. io plugin

    c++ The fastest in the world io What's the way ? See here for details. . At the same time, give a more common way , Just use fread. Then parse the text yourself , Rather than using cin perhaps scanf, See you here : //fast io test #include & ...

  7. SQL Common sentences , Keep it up to date

    More details document query http://www.postgres.cn/docs/9.5/infoschema-columns.html 1.1 Query the properties of a table by its name SELECT * FROM sys.s ...

  8. Guarantee Activity Call... Every time you start create

    original text :https://stackoverflow.com/questions/41766547/run-oncreate-every-time-android-app-is-opened If you ...

  9. Educational Codeforces Round 44 (Rated for Div. 2)

    Topic link :https://codeforces.com/contest/985 ’A.Chess Placing The question : Given a chessboard in one dimension , share n(n Must be an even number ) Lattice . The chessboard is black and white . Now there are... On the chessboard ...

  10. stay properties.xml Define variables in , stay application.xml In this paper, we discuss the problem of value taking

    If application.xml The variables in are assigned default values , At the same time properties.xml Variable assignment in , But after loading, it can't get properties.xml The problem of values in . To solve this problem, we need to add the bold part configuration : & ...