Example #1
0
def create_interactive_examples(component_name, example_code):
    '''Generate an interactive example for this component with callbacks.

    :param (str) component_name: The name of the component as it is
    defined within the package.
    :param (str) example_code: The code for the interactive example.
    '''
    if len(example_code) > 0:
        examples_list = []
        for example in example_code:
            # For each example, extract the description and remove it from the app code.
            # This description will be set as the header and subtext for this component.
            example_string = str(example[0])
            description = re.search(r"\'\'\'(.*?)\'\'\'", example_string, re.S)
            description = re.sub(r"\'\'\'", "", description.group(), 0, re.S)
            example_string = re.sub(r"\'\'\'(.*?)\'\'\'", "", example_string,
                                    0, re.S)

            single_example = html.Div([
                html.Hr(),
                rc.Markdown(description),
                rc.Markdown(example_string),
                html.Div(example[1], className='example-container'),
                html.Hr()
            ])
            examples_list.append(single_example)
        return (examples_list)
    else:
        return []
Example #2
0
def create_default_example(component_name, example_code, styles,
                           component_hyphenated):
    '''Generate a default example for the component-specific page.

    :param (str) component_name: The name of the component as it is
    defined within the package.
    :param (str) example_code: The code for the default example.
    :param (dict) styles: The styles to be applied to the code
    container.

    :rtype (list[object]): The children of the layout for the default
    example.
    '''

    return [
        rc.Markdown(
            'See [{} in action](http://dash-gallery.plotly.host/dash-{}).'.
            format(component_name, component_hyphenated)),
        html.Hr(),
        html.H3("Default {}".format(component_name)),
        html.P("An example of a default {} component without \
        any extra properties.".format(component_name)),
        rc.Markdown(example_code[0]),
        html.Div(example_code[1], className='example-container'),
        html.Hr()
    ]
Example #3
0
def Syntax(children, style=styles.code_container, summary=''):
    code = children
    if not code.startswith('```'):
        code = '```py\n' + code + '\n```'

    if summary:
        return html.Details([
            html.Summary(summary),
            reusable_components.Markdown(code, style=style)
        ],
                            open=True)
    else:
        return reusable_components.Markdown(code, style=style)
Example #4
0
def component_list(package,
                   content_module,
                   base_url,
                   import_alias,
                   component_library,
                   escape_tags=False):
    return [{
        'url':
        tools.relpath('/{}/{}'.format(base_url, component.lower())),
        'name':
        '{}.{}'.format(import_alias, component),
        'description':
        ' '.join([
            'Official examples and reference documentation for {name}.',
            '{which_library}'
        ]).format(
            name='{}.{}'.format(import_alias, component),
            component_library=component_library,
            which_library=('{name} is a {component_library} component.'.format(
                name='{}.{}'.format(import_alias, component),
                component_library=component_library,
            ) if component_library != import_alias else '')).strip(),
        'content':
        (getattr(content_module, component) if
         (content_module is not None
          and hasattr(content_module, component)) else html.Div([
              html.H1(html.Code('{}.{}'.format(import_alias, component))),
              html.H2('Reference & Documentation'),
              rc.Markdown(getattr(package, component).__doc__,
                          escape_tags=escape_tags),
          ]))
    } for component in sorted(dir(package)) if not component.startswith('_')
            and component[0].upper() == component[0]]
Example #5
0
def component_doc(component):
    trimmed_docs = re.sub(
        r'- setProps.*\n', '',
        re.sub(r'Available events: .*', '',
               component.__doc__.split('Keyword arguments:')[-1]))

    return html.Div(className='cytoscape-reference',
                    children=[rc.Markdown(trimmed_docs)])
Example #6
0
 def Display(example_string):
     return html.Div([
         reusable_components.Markdown(
             '```python  \n ' + dedent(example_string).strip() + '  \n```',
             style={'marginBottom': 10, 'borderLeft': 'thin #C8D4E3 solid'}
         ),
         eval(dedent(example_string), scope)
     ])
Example #7
0
def create_examples(examples_data):
    examples = []
    for example in examples_data:
        examples += [
            html.H3(example['param_name'].title()),
            rc.Markdown(example['description']),
            rc.ComponentBlock(example['code']),
            html.Hr()
        ]
    return examples
Example #8
0
 def Display(example_string):
     return html.Div([
         rc.Markdown('```py \n' + dedent(example_string).strip() + '\n ```',
                     style={
                         'marginBottom': 10,
                         'borderLeft': 'thin #C8D4E3 solid'
                     }),
         html.Div(children=eval(dedent(example_string), scope),
                  style={
                      'border': 'thin lightgrey solid',
                      'margin-top': '-10px',
                      'padding': '15px'
                  })
     ])
Example #9
0
def imageComponentBlock(example_string, location, height=None, width=400):
    '''Generate a container that is visually similar to the
    ComponentBlock for components that require an externally hosted image.

    :param (str) example_string: String containing the code that is
    used in the application from the image.
    :param (str) location: The URL of the image.
    :param (int) height: The height of the image.
    :param (int) width: The width of the image.

    :rtype (dict): A dash_html_components div containing the code
    container and the image.

    '''

    try:
        exec(example_string, {})
    except Exception as e:
        print('\nError running\n{}\n{}'.format(
            example_string, ('======================================' +
                             '======================================')))
        raise e

    demo_location = re.match('.*pic_(.*)\.png\?raw=true', location)

    if demo_location is not None:
        demo_location = demo_location.group(1)
    else:
        demo_location = ''

    return html.Div([
        reusable_components.Markdown('```python  \n' + example_string +
                                     '  \n```',
                                     style=styles.code_container),
        html.Div(
            className='example-container',
            children=[
                dcc.Markdown(
                    '> Try a live demo at http://dash-gallery.plotly.host/docs-demos-dashbio/{}'
                    .format(demo_location, demo_location)),
                html.Img(style={
                    'border': 'none',
                    'width': '75%',
                    'max-width': '500px'
                },
                         src=location)
            ])
    ])
Example #10
0
def ComponentBlock(example_string, **kwargs):
    scope = {}
    converted_string = example_string.replace('dcc.',
                                              'component = dcc.').replace(
                                                  'daq.', 'component = daq.')

    for wrapped_component in ['Clustergram', 'ManhattanPlot', 'VolcanoPlot']:
        if wrapped_component not in converted_string:
            converted_string = converted_string.replace(
                'dashbio.', 'component = dashbio.')

    try:
        exec(converted_string, scope)
    except Exception as e:
        print('\nError running\n{}\n{}'.format(
            converted_string, ('======================================' +
                               '======================================')))

        raise e
    return html.Div(
        [
            reusable_components.Markdown('``` python \n' + example_string +
                                         '  \n```',
                                         style=styles.code_container),
            html.Div(
                scope['component'],
                className='example-container',
                style=(({
                    'overflow-x': 'initial'
                }) if ('DatePicker' in example_string
                       or 'Dropdown' in example_string) else
                       ({
                           'overflow-x': 'initial',
                           'padding-bottom': '25px'
                       }) if 'Slider' in example_string else ({
                           'float': 'center'
                       }) if 'ColorPicker' in example_string else (
                           {
                               'padding-left': '30px'
                           }) if 'Tank' in example_string else
                       ({
                           'height': '240px'
                       }) if 'Thermometer' in example_string else {}))
        ])
Example #11
0
def component_list(
        package, content_module, base_url, import_alias,
        component_library, escape_tags=False,
        ad='dash-enterprise-kubernetes.jpg',
        adhref='https://plotly.com/dash/kubernetes/?utm_source=docs&utm_medium=sidebar&utm_campaign=june&utm_content=kubernetes'):
    return [
        {
            'url': tools.relpath('/{}/{}'.format(base_url, component.lower())),
            'name': '{}.{}'.format(import_alias, component),
            'description': ' '.join([
                'Official examples and reference documentation for {name}.',
                '{which_library}'
            ]).format(
                name='{}.{}'.format(import_alias, component),
                component_library=component_library,
                which_library=(
                    '{name} is a {component_library} component.'.format(
                        name='{}.{}'.format(import_alias, component),
                        component_library=component_library,
                    ) if component_library != import_alias else ''
                )
            ).strip(),
            'content': (
                getattr(content_module, component)
                if (content_module is not None and
                    hasattr(content_module, component))
                else html.Div([
                    html.H1(html.Code('{}.{}'.format(
                        import_alias,
                        component
                    ))),
                    html.H2('Reference & Documentation'),
                    rc.Markdown(
                        getattr(package, component).__doc__,
                        escape_tags=escape_tags
                    ),
                ])
            ),
            'ad': ad,
            'adhref': adhref
        } for component in sorted(dir(package))
        if not component.startswith('_') and
        component[0].upper() == component[0]
    ]
Example #12
0
def component_list(package,
                   content_module,
                   base_url,
                   import_alias,
                   escape_tags=False):
    return [{
        'url':
        tools.relpath('/{}/{}'.format(base_url, component.lower())),
        'name':
        '{}.{}'.format(import_alias, component),
        'content':
        (getattr(content_module, component) if
         (content_module is not None
          and hasattr(content_module, component)) else html.Div([
              html.H1(html.Code('{}.{}'.format(import_alias, component))),
              html.H2('Reference & Documentation'),
              reusable_components.Markdown(getattr(package, component).__doc__,
                                           escape_tags=escape_tags),
          ]))
    } for component in sorted(dir(package)) if not component.startswith('_')
            and component[0].upper() == component[0]]
Example #13
0
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd

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

examples = tools.load_examples(__file__)

layout = html.Div([
    rc.Markdown('# DataTable - Python Callbacks'),
    rc.Markdown('''
    ## Backend Paging

    With backend paging, we can load data into our table progressively.
    Instead of loading all of the data at once, we'll only load data
    as the user requests it when they click on the "previous" and "next"
    buttons.

    Since backend paging integrates directly with your Dash callbacks, you can
    load your data from any Python data source.
    '''),
    rc.Markdown(examples['callbacks_paging.py'][0],
                style=styles.code_container),
    html.Div(examples['callbacks_paging.py'][1],
             className='example-container'),
    html.Hr(),
    rc.Markdown('''
    With backend paging, we can have front-end sorting and filtering
Example #14
0
import dash_core_components as dcc
import dash_html_components as html
import dash_bio

from dash_docs import styles
from dash_docs.tutorial.utils.dashbio_docs import generate_docs
from dash_docs import reusable_components

DASHBIO_LIBRARY_HEADING = [
    reusable_components.Markdown('''# Dash Bio'''),
    reusable_components.Markdown('''pip install dash-bio=={}'''.format(
        dash_bio.__version__),
                                 style=styles.code_container),
    reusable_components.Markdown('''
    Dash is a web application framework that provides pure Python abstraction
    around HTML, CSS, and JavaScript.

    Dash Bio is a suite of bioinformatics components that make it simpler to
    analyze and visualize bioinformatics data and interact with them in a Dash
    application.

    The source can be found on GitHub at [plotly/dash-bio](https://github.com/plotly/dash-bio).

    These docs are using Dash Bio version {}.
    '''.format(dash_bio.__version__, dash_bio.__version__))
]

DASHBIO_INSTALL_INSTRUCTIONS = reusable_components.Markdown(
    '''
    ```
    >>> import dash_bio
Example #15
0
layout = reusable_components.Markdown('''
# Writing your own components

One of the really cool things about dash is that
it is built on top of [React.js](https://facebook.github.io/react/),
a JavaScript library for building web components.

The React community is huge. Thousands of components have been built and
released with open source licenses. For example, here are just some of the
[slider components](https://react.rocks/?q=slider) and
[table components](https://react.rocks/?q=tables) that have been published
by the React community, any of which could be adapted into a Dash Component.

## Creating a Component

To create a Dash component, fork our sample component repository and
follow the instructions in the README.md:
[https://github.com/plotly/dash-component-boilerplate](https://github.com/plotly/dash-component-boilerplate)

If you are just getting started with React.js as a Python programmer, please check out our essay
<dccLink href="/react-for-python-developers" children="React for Python Devs"/>.


### How Are Components Converted From React.js to Python?

Dash provides a framework that converts React components
(written in JavaScript) into Python classes that are
compatible with the Dash ecosystem.

On a high level, this is how that works:
- Components in dash are serialized as [JSON](https://www.json.org/).
  To write a dash-compatible component, all of the props
  shared between the Python code and the React code must be serializable as JSON.
  Numbers, Strings, Booleans, or Arrays or Objects containing Numbers, Strings, Booleans.
  For example, JavaScript functions are not valid input arguments.
  In fact, if you try to add a function as a prop to your Dash component, you
  will see that the generated Python code for your component will not include
  that prop as part of your component's accepted list of props.
  (It's not going to be listed in the `Keyword arguments` enumeration or in the
  `self._prop_names` array of the generated Python file for your component).
- By annotating components with React docstrings (not required but helpful
  and encouraged), Dash extracts the information about the component's name,
  properties, and description through [React Docgen](https://github.com/reactjs/react-docgen).
  This is exported as a JSON file (metadata.json).
- At build time, Dash reads this JSON file and dynamically creates Python classes
  that subclass a core Dash component. These classes include argument validation,
  Python docstrings, types, and a basic set of methods. _These classes are
  generated entirely automatically._ A JavaScript developer does not need to
  write _any_ Python in order to generate a component that can be used in the
  Dash ecosystem.
- You will find all of the auto-generated files from the build process in the
  folder named after your component. When you create your Python package, by default any
  non-Python files won't be included in the actual package. To include these files
  in the package, you must list them explicitly in `MANIFEST.in`. That is, `MANIFEST.in`
  needs to contain each JavaScript, JSON, and CSS file that you have included in
  your `my_dash_component/` folder. In the `dash-component-boilerplate` repository,
  you can see that all the javascript for your React component is included in the
  build.js file.
- The Dash app will crawl through the app's `layout` property and check which
  component packages are included in the layout and it will extract that
  component's necessary JavaScript or CSS bundles. Dash will serve these bundles
  to Dash's front-end. These JavaScript bundles are used to render the components.
- Dash's `layout` is serialized as JSON and served to Dash's front-end. This
  `layout` is recursively rendered with these JavaScript bundles and React.


''')
Example #16
0
# -*- coding: utf-8 -*-
import dash_html_components as html
import dash_core_components as dcc
from dash_docs import reusable_components

layout = html.Div(className='gallery',
                  children=[
                      reusable_components.Markdown('''
    ## The Dash App Gallery has moved!

    It is now at [https://dash-gallery.plotly.host/Portal/](https://dash-gallery.plotly.host/Portal/)
    ''')
                  ])
Example #17
0
    rc.Markdown('''
    Dash applications are rendered in the web browser with CSS and JavaScript.
    On page load, Dash serves a small HTML template that includes references to
    the CSS and JavaScript that are required to render the application.
    This chapter covers everything that you need to know about configuring
    this HTML file and about including external CSS and JavaScript in Dash
    applications.

    **Table of Contents**
    - Adding Your Own CSS and JavaScript to Dash Apps
    - Embedding Images in Your Dash Apps
    - Changing the Favicon
    - Adding External CSS and JavaScript
    - Customizing Dash's HTML Index Template
    - Adding Meta Tags
    - Serving Dash's Component Libraries Locally or from a CDN
    - Sample Dash CSS Stylesheet
    ***

    ## Adding Your Own CSS and JavaScript to Dash Apps

    **New in dash 0.22.0**

    Including custom CSS or JavaScript in your Dash apps is simple.
    Just create a folder named `assets` in the root of your app directory
    and include your CSS and JavaScript
    files in that folder. Dash will automatically serve all of the files that
    are included in this folder. By default the url to request the assets will
    be `/assets` but you can customize this with the `assets_url_path` argument
    to `dash.Dash`.

    **Important: For these examples, you need to include `__name__` in your Dash constructor.**

    That is, `app = dash.Dash(__name__)` instead of `app = dash.Dash()`. [Here's why](https://community.plotly.com/t/dash-app-does-not-load-assets-and-app-index-string/12178/10?u=chriddyp).

    ### Example: Including Local CSS and JavaScript

    We'll create several files: `app.py`, a folder named `assets`, and
    three files in that folder:
    ```bash
    - app.py
    - assets/
        |-- typography.css
        |-- header.css
        |-- custom-script.js
    ```
    &nbsp;

    `app.py`

    '''),
Example #18
0
        'tutorial/examples/getting_started_table.py',
        'tutorial/examples/getting_started_viz.py',
        'tutorial/examples/getting_started_markdown.py',
        'tutorial/examples/getting_started_core_components.py',
    ]
]


layout = html.Div([


    reusable_components.Markdown('''
    # Dash Layout

    <blockquote>
    This is the 2nd chapter of the <dccLink children="Dash Tutorial" href="/"/>.
    The <dccLink href="/installation" children="previous chapter"/> covered installation
    and the <dccLink href="/getting-started-part-2" children="next chapter"/> covers Dash callbacks.
    </blockquote>
    '''),


    reusable_components.Markdown('''

    This tutorial will walk you through a fundamental aspect of Dash apps, the
    app `layout`, through {} self-contained apps.

    '''.format(len(examples)).replace('    ', '')),

    reusable_components.Markdown('''***
examples = {
    example:
    tools.load_example('tutorial/examples/cytoscape/{}'.format(example))
    for example in ['usage-phylogeny.py']
}

layout = html.Div([
    reusable_components.Markdown('''
    # Cytoscape with Biopython

    In this chapter, we will show an example of automatically generating a
    phylogenetic tree
    from biopython's `Phylo` object, and enable interactive features such
    as highlighting children clades. The source code is available as [`usage-phylogeny.py`](https://github.com/plotly/dash-cytoscape/blob/master/demos/usage-phylogeny.py),
    and you can find an [online demo here](https://dash-gallery.plotly.host/cytoscape-phylogeny).

    ## Parsing the Phylo object

    The first step is to load the phylogeny tree. We will be using the
    `apaf.xml` file retrieved from [PhyloXML](http://www.phyloxml.org/examples/apaf.xml).

    To load the file, run this (after you made sure that
    biopython was correctly installed):

    '''),
    reusable_components.Markdown('''
    ```py
    from Bio import Phylo
    tree = Phylo.read('data/apaf.xml', 'phyloxml')
    ```
    ''',
                                 style=styles.code_container),
Example #20
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')
])
Example #21
0
    rc.Markdown('''
    # Dash Dev Tools

    Dash Dev Tools is an initiative to make debugging and developing Dash apps more pleasant. This initiative was [sponsored by an organization](http://plotly.com/products/consulting-and-oem/) and you can see our work in our [GitHub project](https://github.com/orgs/plotly/projects/3).

    *dev_tools features are activated by default when you run the app with `app.run_server(debug=True)`*

    ## Hot Reloading

    **New in dash 0.30.0 and dash-renderer 0.15.0**

    By default, Dash includes "hot-reloading". This means that Dash will automatically refresh your browser when you make a change in your Python or CSS code.

    Hot reloading works by running a "file watcher" that examines your working directory to check for changes. When a change is detected, Dash reloads your application in an efficient way automatically. A few notes:
    - Hot reloading is triggered when you _save_ a file.
    - Dash examines the files in your working directory.
    - CSS files are automatically "watched" by examining the `assets/` folder. <dccLink href="/external-resources" children="Learn more about css"/>
    - If only CSS changed, then Dash will only refresh that CSS file.
    - When your Python code has changed, Dash will re-run the entire file and then refresh the application in the browser.
    - If your application initialization is slow, then you might want to consider how to save certain initialization steps to file. For example, if your app initialization downloads a static file from a remote service, perhaps you could include it locally.
    - Hot reloading will not save the application's _state_. For example, if you've selected some items in a dropdown, then that item will be cleared on hot-reload.
    - Hot reloading is configurable through a set of parameters. See the Reference section at the end of this page.

    ## Serving the dev bundles

    Component library bundles are minified by default, if you encounter a front-end error in your code, the variables names will be mangled.
    By serving the dev bundles, you will get the full names.

    ## Dev Tools UI

    **New in dash 0.42.0 and dash-renderer 0.23.0**

    The new Dev Tools UI provides a simple interface, which consolidates both frontend and backend errors into an "error popup" at the top-right corner.
    This could reduce your context switch among *terminal*, *code editor*, *browser* and *browser debug console* while developing a dash app.

    To better understand the interaction of callbacks, we visualize the callback function definitions into
    a DAG (Directed Acyclic Graph). A **Callback Graph** icon is available after clicking the debug icon at the bottom-right corner.

    As upgrading to React 16 since dash-renderer *0.22.0*, we also leverage the new
    [Error Handling](https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html) feature so that all
    Dash React Components get free [Component Props check](https://reactjs.org/docs/typechecking-with-proptypes.html)
    from *dash-renderer*.

    Note: You can disable the check by setting `dev_tools_props_check=False`. But we strongly recommended to fix the props errors:

    > As of React 16, errors that were not caught by any error boundary will result in
    > unmounting of the whole React component tree.

    ## Reference

    The full set of dev tools parameters are included in `app.run_server` or `app.enable_dev_tools`:

    - `debug`, bool, activate all the dev tools.
    - `dev_tools_ui`, bool, set to `False` to explicitly disable dev tools UI in debugger mode (default=True)
    - `dev_tools_props_check`, bool, set to `False` to explicitly disable component props validation (default=True)
    - `dev_tools_hot_reload`, bool, set to `True` to enable hot reload (default=False).
    - `dev_tools_hot_reload_interval`, float, interval in seconds at which the renderer will request the reload hash and update the browser page if it changed. (default=3).
    - `dev_tools_hot_reload_watch_interval`, float, delay in seconds between each walk of the assets folder to detect file changes. (default=0.5 seconds)
    - `dev_tools_hot_reload_max_retry`, int, number of times the reloader is allowed to fail before stopping and sending an alert. (default=8)
    - `dev_tools_silence_routes_logging`, bool, remove the routes access logging from the console.
    - `dev_tools_serve_dev_bundles`, bool, serve the dev bundles.
    - `dev_tools_prune_errors`, bool, simplify tracebacks to just user code, omitting stack frames from Dash and Flask internals. (default=True)

    ### Settings with environment variables

    All the `dev_tools` variables can be set with environment variables, just replace the `dev_tools_` with `dash_` and convert to uppercase.
    This allows you to have different run configs without changing the code.

    Linux/macOS:

    `export DASH_HOT_RELOAD=false`

    Windows:

    `set DASH_DEBUG=true`
    ''')
Example #22
0
import dash_core_components as dcc
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(children=[
    rc.Markdown('''
    # Dash App Life Cycle

    This section describes the lifecycle of a Dash app.

    1. When `python app.py` or `gunicorn app:server` is run, all of the files in a Dash app are executed. This means that if you have a statement such as `df = pd.read_csv('...')`, it is run when the program starts, rather than when the page is loaded. Therefore, if the CSV changes after the program starts, `df` will not be updated until the program restarts. In this case, it is recommended to provide data via a periodic `celery` task or by setting `app.layout` as a function to regenerate the layout with each page load.

    2. When the page loads and the `dash-renderer` starts, it asks the server for both the initial layout (`app.layout`) and a list of all the callbacks registered to the app. This list of callbacks is only provided at page load and can't be modified later, so the app needs to know about all of its callbacks from the beginning even for components that do not exist in the initial layout.
        - Note that this is a recursive process:  the `dash-renderer` collects not only those callbacks whose inputs can be changed directly through user interaction, but also those callbacks whose inputs are outputs of another callback that has already been collected. It's important that the `dash-renderer` collects the entire callback chain up front, or else it wouldn't be able to determine which callbacks are blocking others.

    3. All callbacks that have inputs in currently the app layout are executed. This is known as the "initial call" of the callbacks, and this behavior can be suppressed by using the `prevent_initial_call` attribute.
        - If a Dash app has multiple callbacks, the `dash-renderer` requests callbacks to be executed based on whether or not their inputs might be changed as a result of another callback.

    4. Components in the layout communicate with the `dash-renderer` whenever their state changes. When this occurs, the `dash-renderer` looks to see which callbacks need to be executed as a response to the user input. This can include both callbacks that use the input directly and callbacks whose inputs are outputs of callbacks that use the input directly.
     - Since the `dash-renderer` has introspected the entire callback chain, it can delay the execution of callbacks whose inputs are outputs of callbacks that use the input directly until after callbacks that use the input directly have executed. This minimizes the number of requests the `dash-renderer` needs to make to the server in response to a particular user input.

    5. It is possible for new components to be added to the `app.layout` dynamically as the output of a callback. If these new components are themselves inputs to callback functions, then their appearance in the layout triggers the execution of those callbacks.

''')
])
Example #23
0
import dash_html_components as html
import dash_core_components as dcc
from dash_docs import reusable_components as rc
from dash_docs import tools

layout = html.Div([
    rc.Markdown(u"""
    # Dash Testing

    *New in Dash v1.0*

    *support Dash for R testing added in v1.1.0*

    `dash.testing` \U0001f9ea provides some off-the-rack
    `pytest` [fixtures](https://docs.pytest.org/en/latest/fixture.html)
    and a minimal set of testing **APIs** with our internal crafted
    best practices at the integration level.

    This tutorial does not intend to cover the usage of
    [pytest](https://docs.pytest.org/en/latest/) and
    [Selenium WebDriver](https://www.seleniumhq.org/projects/webdriver/),
    but focuses on how to do a simple integration test with Dash by hosting
    the App server locally and using a Selenium WebDriver to simulate
    the interaction inside a web browser.

    """),
    html.Img(alt='demo',
             src=tools.relpath('assets/images/gallery/dash-testing.gif')),
    rc.Markdown("""

    ## Install
Example #24
0
    rc.Markdown('''
    # Advanced Demos

    __dash_vtk__ provides several advanced examples that should re-enforce what has been described so far.

    We've converted several examples from [PyVista](https://docs.pyvista.org/) to show you how to enable rendering on the client side using __dash_vtk__.

    Then we made several examples using plain VTK for both a CFD example and some medical ones.

    ## Point Cloud creation

    [dash_vtk](https://github.com/plotly/dash-vtk/blob/master/demos/pyvista-point-cloud/app.py) | [PyVista](https://docs.pyvista.org/examples/00-load/create-point-cloud.html)

    ![Preview](/assets/images/vtk/pyvista-point-cloud.jpg)

    ## Terrain following mesh

    [dash_vtk](https://github.com/plotly/dash-vtk/blob/master/demos/pyvista-terrain-following-mesh/app.py) | [PyVista](https://docs.pyvista.org/examples/00-load/terrain-mesh.html)
    ![Preview](/assets/images/vtk/pyvista-terrain-following-mesh.jpg)

    ## VTK dynamic streamlines example

    This example leverages plain VTK on the server side while providing UI controls in __dash__ and leverages __dash_vtk__ to enable local rendering of dynamically computed streamlines inside a wind tunnel.

    [dash_vtk](https://github.com/plotly/dash-vtk/blob/master/demos/usage-vtk-cfd/app.py)

    ![CFD Preview](/assets/images/vtk/usage-vtk-cfd.jpg)

    ## Medical examples

    [Real medical image](https://github.com/plotly/dash-vtk/blob/master/demos/volume-rendering/app.py)

    ![Real medical image](/assets/images/vtk/volume-rendering.jpg)


    [Randomly generated volume](https://github.com/plotly/dash-vtk/blob/master/demos/synthetic-volume-rendering/app.py)

    ![Randomly generated volume](/assets/images/vtk/synthetic-volume-rendering.jpg)

    [Multi-View with slicing](https://github.com/plotly/dash-vtk/blob/master/demos/slice-rendering/app.py)

    ![Multi-View with slicing](/assets/images/vtk/slice-rendering.jpg)

    ''')
Example #25
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.
Example #26
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

layout = [
    reusable_components.Markdown('''
    # Multi-Page Apps and URL Support

    Dash renders web applications as a "single-page app". This means that
    the application does not completely reload when the user navigates the
    application, making browsing very fast.

    There are two new components that aid page navigation:
    <dccLink href="/dash-core-components/location" children="`dash_core_components.Location`"/>
    and <dccLink href="/dash-core-components/link" children="`dash_core_components.Link`"/>.

    `dash_core_components.Location` represents the location bar in your web browser
    through the `pathname` property. Here's a simple example:

    '''),
    reusable_components.Markdown('''
    ```python
    import dash
    import dash_core_components as dcc
    import dash_html_components as html

    print(dcc.__version__) # 0.6.0 or above is required
Example #27
0
import dash_html_components as html
from dash_docs import styles
from dash_docs.tools import load_example

import dash_daq as daq

from dash_docs.simple_doc_generator import generate_docs
from dash_docs import reusable_components as rc, tools

daq_library_heading = rc.Markdown('''
    # Dash DAQ

    Dash is a web application framework that provides pure Python abstraction
    around HTML, CSS, and JavaScript.

    Dash DAQ comprises a robust set of controls that make it simpler to
    integrate data acquisition and controls into your Dash applications.

    The source is on GitHub at [plotly/dash-daq](https://github.com/plotly/dash-daq).

    These docs are using version {}.
    '''.format(daq.__version__))

daq_install_instructions = rc.Markdown('''
    ```py
    >>> import dash_daq as daq
    >>> print(daq.__version__)
    {}
    ```
    '''.format(daq.__version__),
                                       style=styles.code_container)
Example #28
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('dcc.Checklist'),
    rc.Markdown('''
    `dcc.Checklist` is a component for rendering a set of checkboxes.
    See also <dccLink href="/dash-core-components/radioitems" children="RadioItems"/>
    for selecting a single option at a time or
    <dccLink href="/dash-core-components/dropdown" children="Dropdown"/> for
    a more compact view.
    '''),
    rc.ComponentBlock('''import dash_core_components as dcc

dcc.Checklist(
    options=[
        {'label': 'New York City', 'value': 'NYC'},
        {'label': 'Montréal', 'value': 'MTL'},
        {'label': 'San Francisco', 'value': 'SF'}
    ],
    value=['NYC', 'MTL']
)''',
                      style=styles.code_container),
    rc.ComponentBlock('''import dash_core_components as dcc
Example #29
0
import dash_cytoscape

from dash_docs.reusable_components import Section, Chapter
from dash_docs import styles
from dash_docs import tools
from dash_docs import reusable_components

examples = {
    example:
    tools.load_example('tutorial/examples/cytoscape/{}'.format(example))
    for example in ['simple.py']
}

preamble = html.Div([
    reusable_components.Markdown('''
    # Dash Cytoscape

    '''),
    html.Iframe(
        src=
        "https://ghbtns.com/github-btn.html?user=plotly&repo=dash-cytoscape&type=star&count=true&size=large",
        width="160px",
        height="30px",
        style={'border': 'none'}),
    reusable_components.Markdown('''
    > Released on February 5th, 2019**
    >
    > Dash Cytoscape is a graph visualization component for creating easily
    > customizable, high-performance, interactive, and web-based networks. It
    > extends and renders [Cytoscape.js](http://js.cytoscape.org), and
    > offers deep integration with Dash layouts and callbacks, enabling the
    > creation of powerful networks in conjunction with the rich collection of
Example #30
0
    rc.Markdown('''# Performance

This chapter contains several recommendations for improving the performance
of your dash apps.

The main performance limitation of dash apps is likely the callbacks in
the application code itself. If you can speed up your callbacks, your app
will feel snappier.

***

## Memoization



Since Dash's callbacks are functional in nature (they don't contain any state),
it's easy to add memoization caching. Memoization stores the results of a
function after it is called and re-uses the result if the function is called
with the same arguments.

<blockquote>
For a simple example of using memoization in a Dash app to improve
performance, see the "Improving performance with memoization" section
in the <dccLink href="/advanced-callbacks" children="advanced callbacks"/>
chapter.
</blockquote>

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:
'''),