Creating the Callback Function
00:00 Creating a callback function. In the previous section, you defined how the user will interact with your application. In this section of the course, you’ll create the code that will react to these changes and allow dynamic update of the onscreen charts. For that, you’ll be using callback functions.
.callback() function’s overall structure looks like this. The
.callback() decorator’s parameters are two lists. One is a list of outputs which will be returned to the application, and the second is a list of inputs, which are the interactive elements coming from the page.
These are presented as inputs to the function, which processes the data and returns to the application via the callback. Note that the inputs to and outputs from the function are in the order presented in the decorator. Note that the
Input object discussed here is imported from
component_id is the identifier of the element to modify. The
component_property is the property of the element to modify. In this example, the output would update the price chart’s
In a similar way
Input takes two parameters:
component_property. This time, the
component_id is the identifier of the element to watch, and
component_property is the property of that watched element.
Here, you can see the callback decorator that will be used at first. It will watch the region filter and pass the value of that filter to the function. The function will return two values, which will be passed to the application as the price chart’s
figure value and the volume chart’s
This fully explains why the code for the chart in the previous section of the course was missing the
figure value. It’s provided by the callback function when the page initially loads and at any time that those inputs change.
Here you can see abbreviated code for the callback function body. The function takes the
region, which was passed from the input in the decorator, and creates a Boolean mask of data with the regions that match the input value.
03:06 This mask is then applied to the data. Finally, the two nested dictionaries for the figures are created using the filtered data, and these are returned from the function via the decorator to the application itself.
Now that you understand what the code is doing at a high level, you’ll see it being created in full with a complete definition of the nested dictionaries for
With all of these elements in place, run
app.py, and you should be greeted with an interactive page which allows the selection of
region and an automatically updated chart each time a selection is made.
06:16 Now that you have your initial interactivity up and running, in the next section, you’ll see how to add more filters to the dashboard, allowing your users to hone in on exactly the data they’re interested in.
Become a Member to join the conversation.