How the package Dash works in Python?

I’m leaning the package Dash which is the mose popular package about making a webpage of dashboard . The following is the sample code:

from dash import Dash, dcc, html, Input, Output, callback

import plotly.express as px
import json

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = Dash(__name__, external_stylesheets=external_stylesheets)
fig = px.scatter(x=["a", "b", "c"], y=[1, 2, 3])
fig.update_layout(clickmode='event+select')

fig.update_traces(marker_size=20)

app.layout = html.Div([
    dcc.Graph(
        id='basic-interactions',
        figure=fig
    ),
    html.Div(id="hover-data"),
    html.Div(id="click-data"),
])


@callback(
    Output('hover-data', 'children'),
    Input('basic-interactions', 'hoverData'))
def display_hover_data(hoverData):
    return str(hoverData)

@callback(
    Output('click-data', 'children'),
    Input('basic-interactions', 'clickData'))
def display_click_data(clickData):
    return json.dumps(clickData, indent=2)


if __name__ == '__main__':
    app.run(debug=True, port="8081")

I’m trying to understand where the fucntion display_hover_data‘s argument hoverData come from?

Is it come from the post response on url _dash-update-component?

    def _setup_routes(self):
        self._add_url(
            "_dash-component-suites/<string:package_name>/<path:fingerprinted_path>",
            self.serve_component_suites,
        )
        self._add_url("_dash-layout", self.serve_layout)
        self._add_url("_dash-dependencies", self.dependencies)
        self._add_url("_dash-update-component", self.dispatch, ["POST"])
        self._add_url("_reload-hash", self.serve_reload_hash)
        self._add_url("_favicon.ico", self._serve_default_favicon)
        self._add_url("", self.index)

        if jupyter_dash.active:
            self._add_url(
                "_alive_" + jupyter_dash.alive_token, jupyter_dash.serve_alive
            )

        # catch-all for front-end routes, used by dcc.Location
        self._add_url("<path:path>", self.index)

>Solution :

On callabscks it looks like there is a post request to _dash-update-component. For the hover event, the payload for that requests is

{"output":"hover-data.children","outputs":{"id":"hover-data","property":"children"},"inputs":[{"id":"basic-interactions","property":"hoverData","value":{"points":[{"curveNumber":0,"pointNumber":0,"pointIndex":0,"x":"a","y":1,"bbox":{"x0":153.7,"x1":173.7,"y0":340,"y1":360}}]}}],"changedPropIds":["basic-interactions.hoverData"]}

You can get this information from your browser by inspecting the source code, navigating to the network tab, and selecting Fetch/XHR. You can then cause an event to happen by hovering over a point and select it from the list on the left.

enter image description here

You can see the response by select response instead of payload. All browsers have similar tools but I am using Chrome.

Leave a Reply