Пример #1
0
    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.

    '''),

    rc.Syntax(
        examples['graph_callbacks_simple.py'][0],
        summary="""
            Here's an simple example that
            prints these attributes in the screen.
    """),
    rc.Example(examples['graph_callbacks_simple.py'][1]),

    html.Hr(),

    html.H3('Update Graphs on Hover'),

    rc.Syntax(examples['getting_started_crossfilter.py'][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.
    """),
    rc.Example(examples['getting_started_crossfilter.py'][1]),

    rc.Markdown('''
Пример #2
0
    '''),
    rc.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.'''),
    rc.Syntax('''df = pd.DataFrame({
Пример #3
0
# -*- coding: utf-8 -*-
import dash_core_components as dcc
import dash_html_components as html

from dash_docs import styles
from dash_docs import tools
from dash_docs import reusable_components as rc

examples = tools.load_examples(__file__)

layout = html.Div([
    html.H1('dcc.ConfirmDialogProvider Documentation'),
    rc.Markdown('''
    Send a <dccLink href="/dash-core-components/confirmdialog" children="ConfirmDialog"/> when the user
    clicks the children of this component, usually a button.
    '''),
    rc.Syntax(examples['confirm_provider.py'][0]),
    rc.Example(examples['confirm_provider.py'][1]),
    html.H1('dcc.ConfirmDialogProvider Reference'),
    rc.ComponentReference('ConfirmDialogProvider')
])
Пример #4
0
from dash_docs import styles
from dash_docs import tools
from dash_docs import reusable_components as rc

examples = tools.load_examples(__file__)


layout = html.Div(children=[
    html.H3('dcc.Textarea Documentation'),
    dcc.Markdown(
    '''
    `dcc.Textarea` is a wrapper around the [<textarea/> HTML component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea).

    It is like a `dcc.Input` except that allows for multiple lines of text.
    '''
    ),
    html.H2('Simple dcc.Textarea Example'),

    rc.Syntax(examples['textarea_basic.py'][0]),
    rc.Example(examples['textarea_basic.py'][1]),

    html.H2('Update dcc.Textarea callback on button press'),


    rc.Syntax(examples['textarea_state.py'][0]),
    rc.Example(examples['textarea_state.py'][1]),

    html.H2('dcc.Textarea Properties'),
    rc.ComponentReference('Textarea')
])
Пример #5
0
import dash_html_components as html

from dash_docs import tools
from dash_docs import reusable_components as rc

examples = tools.load_examples(__file__)

layout = html.Div([
    html.H1('Advanced Callbacks'),
    rc.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.
    '''),
    rc.Syntax(examples['prevent_update_button.py'][0]),
    rc.Example(examples['prevent_update_button.py'][1]),
    rc.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.
    '''),
    rc.Syntax(examples['prevent_update.py'][0]),
    rc.Example(examples['prevent_update.py'][1]),
    rc.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.
Пример #6
0
    html.H1('Pattern-Matching Callbacks'),
    rc.Markdown('''
    New in Dash 1.11.0!

    The pattern-matching callback selectors `MATCH`, `ALL`, & `ALLSMALLER`
    allow you to write callbacks that respond to or update an
    arbitrary or dynamic number of components.

    ## Simple Example with `ALL`

    This example renders an arbitrary number of `dcc.Dropdown` elements
    and the callback is fired whenever any of the `dcc.Dropdown` elements
    change. Try adding a few dropdowns and selecting their values to see how
    the app updates.
    '''),
    rc.Syntax(examples['simple_all.py'][0]),
    rc.Example(examples['simple_all.py'][1], style={'overflowX': 'initial'}),
    rc.Markdown('''
    Some notes about this example:
    - Notice how the `id` in `dcc.Dropdown` is a _dictionary_ rather than a _string_.
    This is a new feature that we enabled for pattern-matching callbacks
    (previously, IDs had to be strings).
    - In our second callback, we have `Input({'type': 'dropdown', 'index': ALL}, 'value')`.
    This means "match any input that has an ID dictionary where `'type'` is `'dropdown'`
    and `'index'` is _anything_. Whenever the `value` property of any of the
    dropdowns change, send _all_ of their values to the callback."
    - The keys & values of the ID dictionary (`type`, `index`, `filter-dropdown`)
    are arbitrary. This could've be named `{'foo': 'bar', 'baz': n_clicks}`.
    - However, for readability, we recommend using keys like `type`, `index`, or `id`.
    `type` can be used to refer to the class or set dynamic components and
    `index` or `id` could be used to refer _which_ component you are matching
Пример #7
0
import dash_core_components as dcc
import dash_html_components as html

from dash_docs import styles
from dash_docs import tools
from dash_docs import reusable_components as rc

examples = tools.load_examples(__file__)

layout = html.Div([
    html.H1('dcc.Loading Component Documentation'),
    rc.Markdown('''
    Here’s a simple example that wraps the outputs for a couple of `Input`
    components in the `Loading` component.
    As you can see, you can define the type of spinner you would like to show
    (refer to the reference table below for all possible types of spinners).
    You can modify other attributes as well, such as `fullscreen=True`
    if you would like the spinner to be displayed fullscreen.
    Notice that, the Loading component traverses all
    of its children to find a loading state, as demonstrated in the
    second callback, so that even nested children will get picked up.
    '''),
    rc.Syntax(examples['loading_component.py'][0]),
    rc.Example(examples['loading_component.py'][1]),
    rc.Markdown('''
    Please also check out <dccLink href="/loading-states" children="this section on loading states"/> if you want a more customizable experience.
    '''),
    html.H2('dcc.Loading Properties'),
    rc.ComponentReference('Loading')
])
Пример #8
0
    Then, 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.
    '''),

    dcc.Tabs([
        dcc.Tab(
            label='Dash open-source',
            children=[
                rc.Syntax(examples['getting_started_layout_1.py'][0]),
                rc.Example(examples['getting_started_layout_1.py'][1]),
            ]
        ),
        dcc.Tab(
            label='Dash Enterprise Design Kit',
            children=[
                rc.Syntax(
                '''
                import dash
                import dash_design_kit as ddk
                import plotly.express as px
                import pandas as pd

                app = dash.Dash(__name__)
                server = app.server  # expose server variable for Procfile
Пример #9
0
# -*- coding: utf-8 -*-
import dash_core_components as dcc
import dash_html_components as html

from dash_docs import styles
from dash_docs import tools
from dash_docs import reusable_components as rc

examples = tools.load_examples(__file__)

layout = html.Div(children=[
    html.H1('Input Examples and Reference'),
    html.H2('Supported Input Types'),
    rc.Syntax(examples['input_all_types.py'][0]),
    rc.Example(examples['input_all_types.py'][1]),
    html.Br(),
    html.H2('Debounce delays the Input processing'),
    rc.Syntax(examples['input-basic.py'][0]),
    rc.Example(examples['input-basic.py'][1]),
    html.Br(),
    html.H2('Number Input'),
    rc.Markdown("""

    _Fixed and enhanced in Dash v1.1.0_

    Number type is now close to native HTML5 `input` behavior across
    browsers. We also apply a strict number casting in callbacks:
    valid number converts into corresponding number types, and invalid number
    converts into None. E.g.
    `dcc.Input(id='range', type='number', min=2, max=10, step=1)` typing 3 and
    11 will return respectively integer three and None in Python callbacks.
Пример #10
0
    html.H1('Upload Component'),
    rc.Markdown('''
    The Dash upload component allows your app's viewers to upload files,
    like excel spreadsheets or images, into your application.
    Your Dash app can access the contents of an upload by listening to
    the `contents` property of the `dcc.Upload` component.

    `contents` is a base64 encoded string that contains the files contents,
    no matter what type of file: text files, images, zip files,
    excel spreadsheets, etc.

    '''),
    rc.Syntax(examples['upload-datafile.py'][0],
              summary=rc.Markdown('''
        Here's an example that parses CSV or Excel files and displays
        the results in a table. Note that this example uses the
        `DataTable` from the
        [dash-table](https://github.com/plotly/dash-table)
        project.
    ''')),
    rc.Example(examples['upload-datafile.py'][1]),
    html.Hr(),
    rc.Syntax(examples['upload-image.py'][0],
              summary=rc.Markdown('''
        This next example responds to image uploads by displaying them
        in the app with the `html.Img` component.
    ''')),
    rc.Example(examples['upload-image.py'][1]),
    rc.Syntax(examples['upload-gallery.py'][0],
              summary=rc.Markdown('''
        The `children` attribute of the `Upload` component accepts any
        Dash component. Clicking on the children element will trigger the
Пример #11
0
# -*- coding: utf-8 -*-
import dash_core_components as dcc
import dash_html_components as html

from dash_docs import styles
from dash_docs import tools
from dash_docs import reusable_components as rc

examples = tools.load_examples(__file__)

layout = html.Div([
    html.H1('ConfirmDialog component'),
    rc.Markdown('''
    ConfirmDialog is used to display the browser's native "confirm" modal,
    with an optional message and two buttons ("OK" and "Cancel").
    This ConfirmDialog can be used in conjunction with buttons when the user
    is performing an action that should require an extra step of verification.

    See <dccLink href="/dash-core-components/confirmdialogprovider" children="dcc.ConfirmDialogProvider"/>
    for an easier way to display an alert when clicking on an item.
    '''),
    rc.Syntax(examples['confirm.py'][0]),
    rc.Example(examples['confirm.py'][1]),
    html.H2('dcc.ConfirmDialog Properties'),
    rc.ComponentReference('ConfirmDialog')
])
Пример #12
0
    rc.Syntax(dedent('''
    import dash
    from dash.dependencies import Input, Output
    import dash_core_components as dcc
    import dash_html_components as html
    import dash_enterprise_auth as auth


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

    app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

    server = app.server  # Expose the server variable for deployments

    # Standard Dash app code below
    app.layout = html.Div(className='container', children=[

        html.Div([
            html.H2('Sample App', id='header-title', className='ten columns'),
            html.Div(auth.create_logout_button(), className='two columns', style={'marginTop': 30})
        ]),
        html.Div(id='dummy-input', style={'display': 'none'}),

        html.Div([
            html.Div(
                className='four columns',
                children=[
                    dcc.Dropdown(
                        id='dropdown',
                        options=[{'label': i, 'value': i} for i in ['LA', 'NYC', 'MTL']],
                        value='LA'
                    )
            ]),
            html.Div(
                className='eight columns',
                children=[
                    dcc.Graph(id='graph')
                ])
        ])
    ])


    @app.callback(Output('header-title','children'),
                  [Input('dummy-input', 'children')])
    def update_title(_):

        # print user data to the logs
        print(auth.get_user_data())

        # update header with username
        return 'Hello {}'.format(auth.get_username())


    @app.callback(Output('graph', 'figure'),
                  [Input('dropdown', 'value')])
    def update_graph(value):
        return {
            'data': [{
                'x': [1, 2, 3, 4, 5, 6],
                'y': [3, 1, 2, 3, 5, 6]
            }],
            'layout': {
                'title': value,
                'margin': {
                    'l': 60,
                    'r': 10,
                    't': 40,
                    'b': 60
                }
            }
        }

    if __name__ == '__main__':
        app.run_server(debug=True)
    ''')),
Пример #13
0
        '''
        ),

        rc.Markdown('''
        ### Highlighting cells by value with a colorscale like a heatmap
        '''),

        rc.Markdown(
        '''
        This recipe shades cells with `style_data_conditional` and creates a
        legend with HTML components. You'll need to `pip install colorlover`
        to get the colorscales.
        '''
        ),

        rc.Syntax(discrete_background_color_bins_string),

        Display(
        '''
        df = df_wide  # no-display
        (styles, legend) = discrete_background_color_bins(df)

        result = html.Div([
            html.Div(legend, style={'float': 'right'}),
            dash_table.DataTable(
                data=df.to_dict('records'),
                sort_action='native',
                columns=[{'name': i, 'id': i} for i in df.columns],
                style_data_conditional=styles
            ),
        ])
Пример #14
0
    rc.Markdown('''
    The Download component allows files to be directly downloaded from your
    app. These files include, but are not limited to, spreadsheets, images and
    text files , etc. The component opens a download dialog when the data
    property changes.

    Note that the following examples make use of the `prevent_initial_call`
    attribute to prevent the callbacks from being triggered when the app inputs
    are initially rendered. See <dccLink href="../\
    advanced-callbacks#prevent-callbacks-from-being-executed-on-initial-\
    load" children="Advanced Callbacks"/>. for more details.
    '''),
    html.H3('Downloading Content as Strings'),
    rc.Syntax(examples['download-text.py'][0],
              summary=rc.Markdown('''
        Here is an example show how to download content as a string, \
        while showing the raw JSON:
    ''')),
    rc.Example(examples['download-text.py'][1]),
    html.Hr(),
    html.H3('Download Dataframe as CSV file'),
    rc.Syntax(examples['download-dataframe-csv.py'][0],
              summary=rc.Markdown('''
        For downloading dataframes, the many pandas export methods are
        supported. Below we are downloading a dataframe as a CSV:
    ''')),
    rc.Example(examples['download-dataframe-csv.py'][1]),
    html.Hr(),
    html.H3('Download Dataframe as Excel file'),
    rc.Syntax(examples['download-dataframe-xlxs.py'][0],
              summary=rc.Markdown('''
Пример #15
0
    embed a Dash app at a specific route of an existing Flask app.

    In the following example, a Dash app is mounted at the `/dash` route (eg
    `http://localhost:8050/dash`) of a Flask app:
    """),
    rc.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)
        '''),
    rc.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
    any static assets inside an `assets` directory for this Dash app.
    """),
Пример #16
0
    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.

    Note: Throughout this documentation, Python code examples are meant to be saved as files and executed using `python app.py`. These examples are not intended to run in Jupyter notebooks as-is, although most can be modified slightly to function in that environment.

    '''),
    rc.Syntax(examples['getting_started_layout_1.py'][0],
              summary='''
        To get started, create a file named `app.py` with the following code:
    '''),
    rc.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.
    '''),
    rc.Example(examples['getting_started_layout_1.py'][1]),
    rc.Markdown('''
    Note:
Пример #17
0
    - **`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.
    '''),
    rc.Syntax(examples['persistence.py'][0]),
    rc.Example(examples['persistence.py'][1]),
    rc.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.
    '''),
    rc.Syntax(examples['persistence_clear.py'][0]),
    rc.Example(examples['persistence_clear.py'][1]),
    rc.Markdown('''
Пример #18
0
    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:

'''),

    rc.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
    '''),

    rc.Markdown('''

    ***

    Can be rewritten to use JavaScript like so:

'''),

    rc.Syntax(dedent(
Пример #19
0
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:
'''),
    rc.Syntax(examples['performance_flask_caching.py'][0]),
    rc.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.

'''),
    rc.Syntax(examples['performance_flask_caching_dataset.py'][0]),
    rc.Markdown('''

***
Пример #20
0
import dash_html_components as html

from dash_docs import styles
from dash_docs import tools
from dash_docs import reusable_components as rc

examples = tools.load_examples(__file__)

layout = html.Div(children=[
    html.H1('Button Examples and Reference'),
    html.H2('Button Basic Example'),
    rc.Markdown("An example of a default button without any extra properties \
    and `n_clicks` in the callback. `n_clicks` is an integer that represents \
    that number of times the button has been clicked. Note that the original \
    value is `None`."),
    rc.Syntax(examples['button_basic.py'][0]),
    rc.Example(examples['button_basic.py'][1]),
    html.Br(),
    html.H2([
        'Determining which Button Changed with ',
        html.Code('callback_context')
    ]),
    rc.Markdown("This example utilizes the `dash.callback_context` property, \
    to determine which input was changed."),
    rc.Syntax(examples['button_ctx.py'][0]),
    rc.Example(examples['button_ctx.py'][1]),
    html.Br(),
    html.H2('Button Properties'),
    rc.ComponentReference('Button', html)
])
Пример #21
0
# -*- coding: utf-8 -*-
import dash_html_components as html

from dash_docs import tools
from dash_docs import reusable_components as rc

examples = tools.load_examples(__file__)


layout = html.Div([
    html.H1('dcc.Store'),
    rc.Markdown('''
    The `dcc.Store` component is used to store JSON data in the browser.
    '''),
    html.H2('Store clicks example'),
    rc.Syntax(examples['store_clicks.py'][0]),
    rc.Example(examples['store_clicks.py'][1]),

    html.H2('Share data between callbacks'),

    rc.Syntax(examples['store_share.py'][0]),
    rc.Example(examples['store_share.py'][1]),

    rc.Markdown('''
    ## Storage Limitations

    - The maximum browser [storage space](https://demo.agektmr.com/storage/) is determined by the following factors:
        - Mobile or laptop
        - The browser, under which a sophisticated algorithm is implemented within *Quota Management*
        - Storage encoding where UTF-16 can end up saving only half of the size of UTF-8
        - It's generally safe to store up to 2MB in most environments, and 5~10MB in most desktop-only applications.
Пример #22
0
import dash_html_components as html

from dash_docs import tools
from dash_docs import reusable_components as rc

examples = tools.load_examples(__file__)

layout = html.Div([
    html.H1('Advanced Callbacks'),
    rc.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.
    '''),
    rc.Syntax(examples['prevent_update_button.py'][0]),
    rc.Example(examples['prevent_update_button.py'][1]),
    rc.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.
    '''),
    rc.Syntax(examples['prevent_update.py'][0]),
    rc.Example(examples['prevent_update.py'][1]),
    rc.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.