'''), Syntax('''df = pd.DataFrame({ 'a': [1, 2, 3], 'b': [4, 1, 4], 'c': ['x', 'y', 'z'], }) app.layout = html.Div([ dcc.Dropdown( id='dropdown', options=[{'label': i, 'value': i} for i in df['c'].unique()], value='a' ), html.Div(id='output'), ]) @app.callback(Output('output', 'children'), [Input('dropdown', 'value')]) def update_output_1(value): # Here, `df` is an example of a variable that is # "outside the scope of this function". # *It is not safe to modify or reassign this variable # inside this callback.* global df = df[df['c'] == value] # do not do this, this is not safe! return len(df) ''', summary=''' Here is a sketch of an app with a callback that modifies data out of its scope. This type of pattern *will not work reliably* for the reasons outlined above.'''), Syntax('''df = pd.DataFrame({
*** Dash apps are composed of two parts. The first part is the "`layout`" of the app and it describes what the application looks like. The second part describes the interactivity of the application and will be covered in the <dccLink href="/basic-callbacks" children="next chapter"/>. Dash provides Python classes for all of the visual components of the application. We maintain a set of components in the `dash_core_components` and the `dash_html_components` library but you can also [build your own](https://github.com/plotly/dash-component-boilerplate) with JavaScript and React.js. '''), Syntax(examples[0][0], summary=''' To get started, create a file named `app.py` with the following code: '''), reusable_components.Markdown(''' Run the app with ``` $ python app.py ...Running on http://127.0.0.1:8050/ (Press CTRL+C to quit) ``` and visit [http://127.0.0.1:8050/](http://127.0.0.1:8050/) in your web browser. You should see an app that looks like this. '''), Example(examples[0][1]), reusable_components.Markdown(''' Note:
tools.load_example('tutorial/examples/prevent_update.py'), 'prevent-update-button': tools.load_example('tutorial/examples/prevent_update_button.py'), 'last-clicked-button': tools.load_example('tutorial/examples/last_clicked_button.py') } layout = html.Div([ html.H1('Advanced Callbacks'), reusable_components.Markdown(''' ## Catching errors with `PreventUpdate` In certain situations, you don't want to update the callback output. You can achieve this by raising a `PreventUpdate` exception in the callback function. '''), Syntax(examples['prevent-update-button'][0]), Example(examples['prevent-update-button'][1]), reusable_components.Markdown(''' ## Displaying errors with `dash.no_update` This example illustrates how you can show an error while keeping the previous input, using `dash.no_update` to update the output partially. '''), Syntax(examples['prevent-update'][0]), Example(examples['prevent-update'][1]), reusable_components.Markdown(''' ## Determining which `Input` has fired with `dash.callback_context` In addition to event properties like `n_clicks` that change whenever an event happens (in this case a click), there is a global variable `dash.callback_context`, available only inside a callback.
- **`persisted_props`** (list of strings; optional): These are the props whose values will persist. Typically this defaults to all user-editable props, which in many cases is just one (ie `'value'`). `dash-table` has many props users can edit, and all of them except `'data'` are included here by default. Sometimes only a *part* of a prop is saved; this happens with table headers, which are only part of the `columns` prop. The corresponding `persisted_props` value is `'columns.name'`. In the following example, notice that a callback that depends on persisted values receives those persisted values, even if the layout initially provided something else. Also the city is persisted in `localStorage` so will be saved indefinitely, but the neighborhood - which remembers a different value for each city - resets if you open the page in a new tab. '''), Syntax(examples['persistence'][0]), Example(examples['persistence'][1]), reusable_components.Markdown(''' ## Explicitly clearing saved data Persistence continues (subject to `persistence_type`) as long as the component `id`, the `persistence` value, and the prop provided by the server when creating or updating the *entire* component has the same value as it had before the user changed it. But if you have a callback whose `Output` is the specific persisted prop itself, that takes precedence over any saved value. This lets you reset user edits, using `PreventUpdate` or `dash.no_update` until you detect the reset condition. '''), Syntax(examples['persistence_clear'][0]), Example(examples['persistence_clear'][1]), reusable_components.Markdown('''
In the following example, a Dash app is mounted at the `/dash` route (eg `http://localhost:8050/dash`) of a Flask app: """ ), Syntax( ''' import flask import dash import dash_html_components as html server = flask.Flask(__name__) @server.route('/') def index(): return 'Hello Flask app' app = dash.Dash( __name__, server=server, routes_pathname_prefix='/dash/' ) app.layout = html.Div("My Dash app") if __name__ == '__main__': app.run_server(debug=True) ''' ), Markdown( """ > **Note**: it is important to set the `name` parameter of the Dash instance to the value `__name__`, so that Dash can correctly detect the location of
Dash apps are frequently deployed across multiple processes or threads. In these cases, each process or thread contains its own memory, it doesn't share memory across instances. This means that if we were to use `lru_cache`, our cached results might not be shared across sessions. Instead, we can use the [Flask-Caching](https://pythonhosted.org/Flask-Caching/) library which saves the results in a shared memory database like Redis or as a file on your filesystem. Flask-Caching also has other nice features like time-based expiry. Time-based expiry is helpful if you want to update your data (clear your cache) every hour or every day. Here is an example of `Flask-Caching` with Redis: '''), Syntax(examples['performance_flask_caching'][0]), reusable_components.Markdown(''' *** Here is an example that **caches a dataset** instead of a callback. It uses the FileSystem cache, saving the cached results to the filesystem. This approach works well if there is one dataset that is used to update several callbacks. '''), Syntax(examples['performance_flask_caching_dataset']), reusable_components.Markdown(''' ***
Dash components are described declaratively by a set of attributes. All of these attributes can be updated by callback functions, but only a subset of these attributes are updated through user interaction, such as when you click on an option in a `dcc.Dropdown` component and the `value` property of that component changes. The `dcc.Graph` component has four attributes that can change through user-interaction: `hoverData`, `clickData`, `selectedData`, `relayoutData`. These properties update when you hover over points, click on points, or select regions of points in a graph. '''), Syntax(examples['simple-graph-events'][0], summary=""" Here's an simple example that prints these attributes in the screen. """), Example(examples['simple-graph-events'][1]), html.Hr(), html.H3('Update Graphs on Hover'), Syntax(examples['world-indicators'][0], summary=""" Let's update our world indicators example from the previous chapter by updating time series when we hover over points in our scatter plot. """), Example(examples['world-indicators'][1]), reusable_components.Markdown(''' Try mousing over the points in the scatter plot on the left. Notice how the line graphs on the right update based off of the point that you are hovering over.
other optimization is possible, the callback can be modified to be run directly in the browser instead of a making a request to Dash. The syntax for the callback is almost exactly the same; you use `Input` and `Output` as you normally would when declaring a callback, but you also define a JavaScript function as the first argument to the `@app.callback` decorator. For example, the following callback: '''), Syntax(''' @app.callback( Output('out-component', 'value'), [Input('in-component1', 'value'), Input('in-component2', 'value')] ) def large_params_function(largeValue1, largeValue2): largeValueOutput = someTransform(largeValue1, largeValue2) return largeValueOutput '''), reusable_components.Markdown(''' *** Can be rewritten to use JavaScript like so: '''), Syntax(''' from dash.dependencies import Input, Output app.clientside_callback(