Пример #1
0
    This report was written in Python with the Dash framework.
    Dash abstracts away all of the server logic, API calls, CSS,
    HTML, and Javascript that is usually required to produce a rich web
    application. This application was written in a single python file
    containing around 500 lines of code. This includes the data analysis,
    markup, and interactive visualizations. See for yourself below.

    Interested in what you see?
    [Get in touch](https://plot.ly/products/consulting-and-oem/).
    '''.replace('  ', ''),
                 className='container',
                 containerProps={'style': {
                     'maxWidth': '650px'
                 }}),
    html.Div(dcc.SyntaxHighlighter(open('report_nyt_255.py', 'r').read(),
                                   language='python'),
             className='container',
             style={
                 'maxWidth': '650px',
                 'borderLeft': 'thin solid lightgrey'
             })
])

app.layout = layout


@app.callback(Output('filtered-content', 'children'),
              [Input('category-filter', 'value')])
def filter(selected_values):
    figure = create_figure(
        list(df_jobs[df_jobs.nytlabel.isin(selected_values)].cescode)
Пример #2
0
    def test_gallery(self):
        app = dash.Dash(__name__)

        app.layout = html.Div([
            html.Div(id='waitfor'),
            html.Label('Upload'),
            dcc.Upload(),
            html.Label('Dropdown'),
            dcc.Dropdown(options=[{
                'label': 'New York City',
                'value': 'NYC'
            }, {
                'label': u'Montréal',
                'value': 'MTL'
            }, {
                'label': 'San Francisco',
                'value': 'SF'
            }, {
                'label': u'北京',
                'value': u'北京'
            }],
                         value='MTL',
                         id='dropdown'),
            html.Label('Multi-Select Dropdown'),
            dcc.Dropdown(options=[{
                'label': 'New York City',
                'value': 'NYC'
            }, {
                'label': u'Montréal',
                'value': 'MTL'
            }, {
                'label': 'San Francisco',
                'value': 'SF'
            }, {
                'label': u'北京',
                'value': u'北京'
            }],
                         value=['MTL', 'SF'],
                         multi=True),
            html.Label('Radio Items'),
            dcc.RadioItems(options=[{
                'label': 'New York City',
                'value': 'NYC'
            }, {
                'label': u'Montréal',
                'value': 'MTL'
            }, {
                'label': 'San Francisco',
                'value': 'SF'
            }, {
                'label': u'北京',
                'value': u'北京'
            }],
                           value='MTL'),
            html.Label('Checkboxes'),
            dcc.Checklist(options=[{
                'label': 'New York City',
                'value': 'NYC'
            }, {
                'label': u'Montréal',
                'value': 'MTL'
            }, {
                'label': 'San Francisco',
                'value': 'SF'
            }, {
                'label': u'北京',
                'value': u'北京'
            }],
                          values=['MTL', 'SF']),
            html.Label('Text Input'),
            dcc.Input(value='MTL', type='text'),
            html.Label('Slider'),
            dcc.Slider(
                min=0,
                max=9,
                marks={
                    i: 'Label {}'.format(i) if i == 1 else str(i)
                    for i in range(1, 6)
                },
                value=5,
            ),
            html.Label('Graph'),
            dcc.Graph(id='graph',
                      figure={
                          'data': [{
                              'x': [1, 2, 3],
                              'y': [4, 1, 4]
                          }],
                          'layout': {
                              'title': u'北京'
                          }
                      }),
            html.Label('DatePickerSingle'),
            dcc.DatePickerSingle(id='date-picker-single',
                                 date=datetime(1997, 5, 10)),
            html.Label('DatePickerRange'),
            dcc.DatePickerRange(id='date-picker-range',
                                start_date=datetime(1997, 5, 3),
                                end_date_placeholder_text='Select a date!'),
            html.Label('TextArea'),
            dcc.Textarea(placeholder='Enter a value... 北京',
                         style={'width': '100%'}),
            html.Label('Markdown'),
            dcc.Markdown('''
                #### Dash and Markdown

                Dash supports [Markdown](http://commonmark.org/help).

                Markdown is a simple way to write and format text.
                It includes a syntax for things like **bold text** and *italics*,
                [links](http://commonmark.org/help), inline `code` snippets, lists,
                quotes, and more.

                北京
            '''.replace('    ', '')),
            dcc.Markdown(['# Line one', '## Line two']),
            dcc.Markdown(),
            dcc.SyntaxHighlighter(dedent('''import python
                print(3)'''),
                                  language='python'),
            dcc.SyntaxHighlighter(['import python', 'print(3)'],
                                  language='python'),
            dcc.SyntaxHighlighter()
        ])
        self.startServer(app)

        self.wait_for_element_by_css_selector('#waitfor')

        self.snapshot('gallery')

        self.driver.find_element_by_css_selector(
            '#dropdown .Select-input input').send_keys(u'北')
        self.snapshot('gallery - chinese character')
Пример #3
0
import os
import dash_core_components as dcc
import dash_html_components as html

if 'DYNO' in os.environ:
    app_name = os.environ['DASH_APP_NAME']
else:
    app_name = 'dash-animationplot'

layout = html.Div([
    dcc.SyntaxHighlighter(language='python',
                          children=open('apps/main.py', 'r').read()),
])
Пример #4
0
The code behind the template is available in the
[plotly/dash-components-archetype](https://github.com/plotly/dash-components-archetype)
repository on GitHub.

### Step 1 - Prerequisites

You'll need Node, NPM, and Python installed.
Components are built with [React.js](https://facebook.github.io/react/).

> If you're just getting started, we've written a great
[React.js tutorial](https://academy.plot.ly/) as part of our open source academy.

### Step 2 - Install Builder
'''),
    dcc.SyntaxHighlighter('''$ npm install -g builder-init''',
                          language='bash',
                          customStyle=styles.code_container),
    dcc.Markdown('''### Step 3 - Initialize a Project'''),
    dcc.SyntaxHighlighter('''$ builder-init dash-components-archetype''',
                          language='bash',
                          customStyle=styles.code_container),
    dcc.Markdown('''
Builder will initialize a folder containing the boilerplate
of a dash component package.

This will walk you through a series of prompts about your package like
the name and description of the project. The name of the project will be
the name of the Python package, with hyphens replaced by underscores.
For example, if the name is `acme-components` then the Python package will
end up being `acme_components`, importable like `import acme_components`.
Пример #5
0
Components in Dash usually update through user interaction:
selecting a dropdown, dragging a slider, hovering over points.

If you're building an application for monitoring, you may want to update
components in your application every few seconds or minutes.

The `dash_core_components.Interval` element allows you to update components
on a predefined interval.

This example pulls data from live satellite feeds and updates the graph
and the text every second.
'''),
    dcc.SyntaxHighlighter(
        examples[0][0],
        language='python',
        customStyle={'borderLeft': 'thin solid lightgrey'}
    ),
    html.Div(examples[0][1], className="example-container"),

dcc.Markdown('''

***

## Updates on Page Load

By default, Dash apps store the `app.layout` in memory. This ensures that the
`layout` is only computed once, when the app starts.

If you set `app.layout` to a function, then you can serve a dynamic layout
on every page load.
Пример #6
0
import dash_core_components as dcc
import dash_html_components as html
from tutorial import styles
from tutorial.utils.dashbio_docs import generate_docs

import dash_bio

dashbio_library_heading = [
    dcc.Markdown('''# Dash Bio'''),
    dcc.SyntaxHighlighter('''pip install dash-bio=={}'''.format(
        dash_bio.__version__),
                          customStyle=styles.code_container),
    dcc.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 {}.
    '''.replace('    ', '').format(dash_bio.__version__, dash_bio.__version__))
]

dashbio_install_instructions = dcc.SyntaxHighlighter(
    '''>>> import dash_bio
    >>> print(dash_bio.__version__)
    {}'''.replace('    ', '').format(dash_bio.__version__),
    customStyle=styles.code_container)
Пример #7
0
from textwrap import dedent as s

from tutorial import styles

layout = html.Div([
    dcc.Markdown('''
    # Dash Installation

    In your terminal, install several dash libraries.
    These libraries are under active development,
    so install and upgrade frequently.
    Python 2 and 3 are supported.'''.replace('    ', '')),
    dcc.SyntaxHighlighter('''pip install dash=={}  # The core dash backend
        pip install dash-html-components=={}  # HTML components
        pip install dash-core-components=={}  # Supercharged components
        pip install dash-table=={}  # Interactive DataTable component (new!)
    '''.replace('    ', '').format(dash.__version__, html.__version__,
                                   dcc.__version__, dash_table.__version__),
                          customStyle=styles.code_container),
    html.Div([
        'Ready? Now, let\'s ',
        dcc.Link('make your first Dash app', href='/getting-started'), '.'
    ]),
    html.Hr(),
    dcc.Markdown(
        s('''
    > A quick note on checking your versions and on upgrading.
    > These docs are run using the versions listed above and these
    > versions should be the latest versions available.
    > To check which version that you have installed, you can run e.g.
    > ```
Пример #8
0
    around HTML, CSS, and JavaScript.

    Instead of writing HTML or using an HTML templating engine,
    you compose your layout using Python structures with the
    `dash-html-components` library.

    The source for this library is on GitHub: [plotly/dash-html-components](https://github.com/plotly/dash-html-components).

    Here is an example of a simple HTML structure:
    '''.replace('    ', '')),
    dcc.SyntaxHighlighter('''import dash_html_components as html

html.Div([
    html.H1('Hello Dash'),
    html.Div([
        html.P('Dash converts Python classes into HTML'),
        html.P('This conversion happens behind the scenes by Dash\'s JavaScript front-end')
    ])
])''',
                          language='python',
                          customStyle={'borderLeft': 'thin solid lightgrey'}),
    html.Div('which gets converted (behind the scenes) into the '
             'following HTML in your web-app:'),
    dcc.SyntaxHighlighter('''<div>
    <h1>Hello</h1>
    <div>
        <p>Dash converts Python classes into HTML</p>
        <p>This conversion happens behind the scenes by Dash's JavaScript front-end</p>
    </div>
</div>''',
                          language='python',
Пример #9
0
def generate_instructions(chapter, platform):
    if chapter == 'ssh':
        return [
            dcc.Markdown(
                s('''
                You will deploy your Dash code to Plotly On-Premise using Git
                with SSH.
            ''')),
            (dcc.Markdown(
                s('''
                These instructions assume that you are using
                **Git Bash** on Windows, which is included in the
                official [Git for Windows release](https://git-scm.com/download/win).
            ''')) if platform == 'Windows' else ''),
            dcc.Markdown(
                s('''

                ***

                ### Generate a new SSH key

                If you already have an SSH key that you've used in other
                services, you can use that key instead of generating a new one.

            ''')),
            dcc.Markdown('**1. Open Git Bash**' if platform ==
                         'Windows' else '**1. Open Terminal**'),
            dcc.Markdown(
                s('''
                **2. Generate Key**

                This command will walk you
                through a few instructions.
            ''')),
            dcc.SyntaxHighlighter(
                ('$ ssh-keygen -t rsa -b 4096 -C "*****@*****.**"'),
                customStyle=styles.code_container,
                language='python'),
            dcc.Markdown(
                s('''
                ***

                ### Add your SSH key to the ssh-agent

                **1. Ensure the ssh-agent is running:**
            ''')),
            dcc.SyntaxHighlighter(
                ('$ eval $(ssh-agent -s)'
                 if platform == 'Windows' else '$ eval "$(ssh-agent -s)"'),
                customStyle=styles.code_container,
                language='python'),
            dcc.Markdown(
                s('''
                **2. Run `ssh-add`**

                Replace `id_rsa` with the name of the key that you
                created above if it is different.
            ''')),
            dcc.SyntaxHighlighter(
                ('$ ssh-add ~/.ssh/id_rsa'
                 if platform == 'Windows' else '$ ssh-add -K ~/.ssh/id_rsa'),
                customStyle=styles.code_container,
                language='python'),
            dcc.Markdown(
                s('''
                ***

                ### Add your SSH public key your Dash App Manager
            ''')),
            dcc.Markdown(
                s('''
                **1. Copy the SSH key to your clipboard.**

                Replace `id_rsa.pub` with the name of the key that you
                created above if it is different.

            ''')),
            dcc.SyntaxHighlighter((
                '$ clip < ~/.ssh/id_rsa.pub' if platform == 'Windows' else
                '$ pbcopy < ~/.ssh/id_rsa.pub' if platform == 'Mac' else
                '$ sudo apt-get install xclip\n$ xclip -sel clip < ~/.ssh/id_rsa.pub'
            ),
                                  customStyle=styles.code_container,
                                  language='python'),
            dcc.Markdown(
                s('''
                **2. Open the Dash App Manager**

                You can find the Dash App Manager by clicking on "Dash App" in your
                Plotly On-Premise's "Create" menu.

                > *The Dash App item in the Create menu takes you to the Dash App Manager*
            ''')),
            html.Img(
                alt="Dash App Create Menu",
                src=
                "https://github.com/plotly/dash-docs/raw/master/images/dash-create-menu.png",
                style={
                    'width': '100%',
                    'border': 'thin lightgrey solid',
                    'border-radius': '4px'
                }),
            dcc.Markdown(
                s('''
                **3. Paste your key into the Dash App Manager's SSH key field.**
            ''')),
            dcc.Markdown(
                s('''
                > *The Dash App Manager's SSH Key Interface. Copy and paste
                > your public key in this interface and click "Update".*
            ''')),
            html.Img(
                alt="Dash App Manager Public Key Interface",
                src=
                "https://github.com/plotly/dash-docs/raw/master/images/dash-app-manager-ssh-key.png",
                style={
                    'width': '100%',
                    'border': 'thin lightgrey solid',
                    'border-radius': '4px'
                }),
            dcc.Markdown(
                s('''
                ***

                ### Modify SSH Config
                Next, specify a custom port in your SSH config. By default, this should be
                `3022` but your server administrator may have set it to something different.

                This file is located in `~/.ssh/config`. If it's not there, then create it.
                Add the following lines to
                this file, replacing `your-dash-app-manager` with the domain of
                your Dash App Manager (without `http://` or `https://`).
            ''')),
            dcc.SyntaxHighlighter('''Host your-dash-app-manager
    Port 3022''',
                                  customStyle=styles.code_container),
            (dcc.Markdown(
                '''If you're having trouble opening this file, you can run `$ open ~/.ssh/config`
            which will open the file using your default editor. If the file doesn't exist,
            then you can open that hidden folder with just `$ open ~/.ssh`''')
             if platform == 'Mac' else ''),
            dcc.Markdown(
                s('''
                ***

                Next, proceed to Part 2 to intialize your app on Plotly On-Premise.

            '''))
        ]
    elif chapter == 'create-app':
        return [
            dcc.Markdown(
                s('''

                **1. Visit the Dash App Manager**

                **2. Add an app**

                Click on `Add an app` and enter a name for your app.
                The app's name will be part of the URL of your app.
            ''')),
            html.Img(
                alt="Dash App Manager Add App Interface",
                src=
                "https://github.com/plotly/dash-docs/raw/master/images/dash-app-manager-empty.png",
                style={
                    'width': '100%',
                    'border': 'thin lightgrey solid',
                    'border-radius': '4px'
                }),
            dcc.Markdown(
                s('''
                ***

                Next, proceed to Part 3 to deploy your app

            '''))
        ]

    elif chapter == 'deployment':
        return [
            dcc.Markdown(
                s('''

                #### Download the Sample App from GitHub

                Clone the [Dash On Premise Sample App](https://github.com/plotly/dash-on-premise-sample-app) from GitHub.

            ''')), ('In Git Bash, run: ' if platform == 'Windows' else ''),
            dcc.SyntaxHighlighter(s('''
                $ git clone https://github.com/plotly/dash-on-premise-sample-app.git
                '''),
                                  customStyle=styles.code_container),
            dcc.Markdown(
                s('''

                ***

                #### Configure your Plotly On-Premise server to be your Git remote

                The following command will create a remote host to your new app on
                Plotly On-Premise.
            ''')),
            dcc.SyntaxHighlighter(s('''$ cd dash-on-premise-sample-app
                $ git remote add plotly dokku@your-dash-app-manager:your-dash-app-name'''
                                    ),
                                  customStyle=styles.code_container,
                                  language='python'),
            dcc.Markdown(
                s('''
                Replace `your-dash-app-name` with the name of your Dash app that you supplied
                in the Dash app manager and `your-dash-app-manager` with the domain of the
                Dash App Manager.

                For example, if your Dash app name was `my-first-dash-app`
                and the domain of your organizations Dash App Manager was `dash.plotly.acme-corporation.com`,
                then this command would be
                `git remote add plotly [email protected]:my-first-dash-app`.

            ''')),
            dcc.Markdown(
                s('''***

                #### Modify `config.py`

                Read through `config.py` and modify the values as necessary.
                If Dash On-Premise was set up with "path-based routing"
                (the default), then you will just need to change the
                `DASH_APP_NAME` to be equal to the name of the Dash app that you
                set earlier.
            ''')),
            dcc.Markdown(
                s('''
                ***

                #### Deploying Changes

                After you have modified `config.py`, you are ready to upload
                this folder to your Dash On-Premise server.
                Files are transferred to the server using `git`:
            ''')),
            dcc.SyntaxHighlighter(s('''$ git status # view the changed files
                $ git diff # view the actual changed lines of code
                $ git add .  # add all the changes
                $ git commit -m 'a description of the changes'
                $ git push plotly master
                '''),
                                  customStyle=styles.code_container,
                                  language='python'),
            dcc.Markdown(
                s('''
                This commands will push the code in this folder to the
                Dash On-Premise server and while doing so, will install the
                necessary python packages and run your application
                automatically.

                Whenver you make changes to your Dash code,
                you will need to run those `git` commands above.

                If you install any other Python packages, add those packages to
                the `requirements.txt` file. Packages that are included in this
                file will be installed automatically by the Plotly On-Premise
                server.

                You can now modify `app.py` with your own custom Dash
                application code.
            '''))
        ]
    elif chapter == 'auth':
        return [
            dcc.Markdown(
                s('''
            The `dash-auth` package provides login through your Plotly
            On-Premise accounts.

            #### Modify the `config.py` file

            This file contains several settings that are used in your app.
            It's kept in a separate file so that it's easy for you to
            transfer from app to app.
            *Read through this file and modify the variables as appropriate.*

            ''')),
            dcc.Markdown(
                s('''
            #### Redeploy your app

            Your app should now have a Plotly On-Premise login screen.
            You can manage the permissions of the app in your list of files
            at `https://<your-plotly-domain>/organize`.
            '''))
        ]
Пример #10
0
    Installation
    ''', id='installation'),

    dcc.Markdown('''

    In your terminal, install several dash libraries.
    These libraries are under active development,
    so install and upgrade frequently.
    Python 2 and 3 are supported.'''.replace('    ', '')),

    dcc.SyntaxHighlighter('''pip install dash=={}  # The core dash backend
        pip install dash-renderer=={}  # The dash front-end
        pip install dash-html-components=={}  # HTML components
        pip install dash-core-components=={}  # Supercharged components
        pip install plotly --upgrade  # Latest Plotly graphing library
    '''.replace('    ', '').format(
        dash.__version__,
        dash_renderer.__version__,
        html.__version__,
        dcc.__version__,
        plotly.__version__
    ), customStyle=styles.code_container),

    html.H2('''
    Dash App Layout
    ''', id='dash-app-layout'),

    dcc.Markdown('''***

    #### Generating HTML with Dash

    Dash apps are composed of two parts. The first part is the "`layout`" of
def generate_instructions(chapter, platform):
    if chapter == 'ssh':
        return [
            dcc.Markdown(
                s('''
                You will deploy your Dash code to Plotly Enterprise using Git
                with SSH.
            ''')),
            (dcc.Markdown(
                s('''
                These instructions assume that you are using
                **Git Bash** on Windows, which is included in the
                official [Git for Windows release](https://git-scm.com/download/win).
            ''')) if platform == 'Windows' else ''),
            dcc.Markdown(
                s('''

                ***

                ### Generate a new SSH key

                If you already have an SSH key that you've used in other
                services, you can use that key instead of generating a new one.

            ''')),
            dcc.Markdown('**1. Open Git Bash**' if platform ==
                         'Windows' else '**1. Open Terminal**'),
            dcc.Markdown(
                s('''
                **2. Generate Key**

                This command will walk you
                through a few instructions.
            ''')),
            dcc.SyntaxHighlighter(
                ('$ ssh-keygen -t rsa -b 4096 -C "*****@*****.**"'),
                customStyle=styles.code_container,
                language='python'),
            dcc.Markdown(
                s('''
                ***

                ### Add your SSH key to the ssh-agent

                **1. Ensure the ssh-agent is running:**
            ''')),
            dcc.SyntaxHighlighter(
                ('$ eval $(ssh-agent -s)'
                 if platform == 'Windows' else '$ eval "$(ssh-agent -s)"'),
                customStyle=styles.code_container,
                language='python'),
            dcc.Markdown(
                s('''
                **2. Run `ssh-add`**

                Replace `id_rsa` with the name of the key that you
                created above if it is different.
            ''')),
            dcc.SyntaxHighlighter(
                ('$ ssh-add ~/.ssh/id_rsa'
                 if platform == 'Windows' else '$ ssh-add -k ~/.ssh/id_rsa'),
                customStyle=styles.code_container,
                language='python'),
            dcc.Markdown(
                s('''
                ***

                ### Add your SSH public key your Dash Deployment Server
            ''')),
            dcc.Markdown(
                s('''
                **1. Copy the SSH key to your clipboard.**

                Replace `id_rsa.pub` with the name of the key that you
                created above if it is different.

            ''')),
            dcc.SyntaxHighlighter((
                '$ clip < ~/.ssh/id_rsa.pub' if platform == 'Windows' else
                '$ pbcopy < ~/.ssh/id_rsa.pub' if platform == 'Mac' else
                '$ sudo apt-get install xclip\n$ xclip -sel clip < ~/.ssh/id_rsa.pub'
            ),
                                  customStyle=styles.code_container,
                                  language='python'),
            dcc.Markdown(
                s('''
                **2. Open the Dash Deployment Server**

                You can find the Dash Deployment Server by clicking on "Dash App" in your
                Plotly Enterprise's "Create" menu.

                > *The Dash App item in the Create menu takes you to the Dash Deployment Server*
            ''')),
            html.Img(
                alt='Dash App Create Menu',
                src=
                'https://github.com/plotly/dash-docs/raw/master/images/dash-create-menu.png',
                style={
                    'width': '100%',
                    'border': 'thin lightgrey solid',
                    'border-radius': '4px'
                }),
            dcc.Markdown(
                s('''
                **3. Paste your key into the Dash Deployment Server's SSH key field.**
            ''')),
            dcc.Markdown(
                s('''
                > *The Dash Deployment Server's SSH Key Interface. Copy and paste
                > your public key in this interface and click "Update".*
            ''')),
            html.Img(
                alt='Dash Deployment Server Public Key Interface',
                src=
                'https://github.com/plotly/dash-docs/raw/master/images/dash-app-manager-ssh-key.png',
                style={
                    'width': '100%',
                    'border': 'thin lightgrey solid',
                    'border-radius': '4px'
                }),
            dcc.Markdown(
                s('''
                ***

                ### Modify SSH Config
                Next, specify a custom port in your SSH config. By default, this should be
                `3022` but your server administrator may have set it to something different.

                This file is located in `~/.ssh/config`. If it's not there, then create it.
                Add the following lines to
                this file, replacing `your-dash-app-manager` with the domain of
                your Dash Deployment Server (without `http://` or `https://`).
            ''')),
            dcc.SyntaxHighlighter('''Host your-dash-app-manager
    Port 3022''',
                                  customStyle=styles.code_container),
            (dcc.Markdown(
                '''If you're having trouble opening this file, you can run `$ open ~/.ssh/config`
            which will open the file using your default editor. If the file doesn't exist,
            then you can open that hidden folder with just `$ open ~/.ssh`''')
             if platform == 'Mac' else ''),
            (dcc.Markdown(
                '''Please be careful not to save your SSH config as a .txt file as
            it will not be recognized by Git when deploying your applications. If you are using
            Notepad to create your SSH config, you can force the removal of the .txt extension
            by naming the file "config", including the quotes, in the Save As dialog box.'''
            ) if platform == 'Windows' else ''),
            dcc.Markdown(
                s('''
                ***

                Next, proceed to Part 2 to initialize your app on Plotly Enterprise.

            '''))
        ]
    elif chapter == 'create-app':
        return [
            dcc.Markdown(
                s('''

                **1. Visit the Dash Deployment Server**

                **2. Add an app**

                Click on `Add an app` and enter a name for your app.
                The app's name will be part of the URL of your app.
            ''')),
            html.Img(
                alt='Dash Deployment Server Add App Interface',
                src=
                'https://github.com/plotly/dash-docs/raw/master/images/dash-app-manager-empty.png',
                style={
                    'width': '100%',
                    'border': 'thin lightgrey solid',
                    'border-radius': '4px'
                }),
            dcc.Markdown(
                s('''
                ***

                Next, proceed to Part 3 to deploy your app

            '''))
        ]

    elif chapter == 'deployment':
        return [
            dcc.Markdown(
                s('''

                #### Download the Sample App from GitHub

                Clone the [Dash On Premise Sample App](https://github.com/plotly/dash-on-premise-sample-app) from GitHub.

            ''')), ('In Git Bash, run: ' if platform == 'Windows' else ''),
            dcc.SyntaxHighlighter(s('''
                $ git clone https://github.com/plotly/dash-on-premise-sample-app.git
                '''),
                                  customStyle=styles.code_container),
            dcc.Markdown(
                s('''

                ***

                #### Configure your Plotly Enterprise server to be your Git remote

                The following command will create a remote host to your new app on
                Plotly Enterprise.
            ''')),
            dcc.SyntaxHighlighter(s('''$ cd dash-on-premise-sample-app
                $ git remote add plotly dokku@your-dash-app-manager:your-dash-app-name'''
                                    ),
                                  customStyle=styles.code_container,
                                  language='python'),
            dcc.Markdown(
                s('''
                Replace `your-dash-app-name` with the name of your Dash app that you supplied
                in the Dash Deployment Server and `your-dash-app-manager` with the domain of the
                Dash Deployment Server.

                For example, if your Dash app name was `my-first-dash-app`
                and the domain of your organizations Dash Deployment Server was `dash.plotly.acme-corporation.com`,
                then this command would be
                `git remote add plotly [email protected]:my-first-dash-app`.

            ''')),
            dcc.Markdown(
                s('''***

                #### Modify `config.py`

                Read through `config.py` and modify the values as necessary.
                If Dash Deployment Server was set up with "path-based routing"
                (the default), then you will just need to change the
                `DASH_APP_NAME` to be equal to the name of the Dash app that you
                set earlier.
            ''')),
            dcc.Markdown(
                s('''
                ***

                #### Deploying Changes

                After you have modified `config.py`, you are ready to upload
                this folder to your Dash Deployment Server.
                Files are transferred to the server using `git`:
            ''')),
            dcc.SyntaxHighlighter(s('''$ git status # view the changed files
                $ git diff # view the actual changed lines of code
                $ git add .  # add all the changes
                $ git commit -m 'a description of the changes'
                $ git push plotly master
                '''),
                                  customStyle=styles.code_container,
                                  language='python'),
            dcc.Markdown(
                s('''
                This commands will push the code in this folder to the
                Dash Deployment Server and while doing so, will install the
                necessary python packages and run your application
                automatically.

                Whenever you make changes to your Dash code,
                you will need to run those `git` commands above.

                If you install any other Python packages, add those packages to
                the `requirements.txt` file. Packages that are included in this
                file will be installed automatically by the Plotly Enterprise
                server.

                You can now modify `app.py` with your own custom Dash
                application code.
            '''))
        ]
    elif chapter == 'auth':
        return [
            dcc.Markdown(
                s('''
            The `dash-auth` package provides login through your Plotly
            Enterprise accounts.

            #### Modify the `config.py` file

            This file contains several settings that are used in your app.
            It's kept in a separate file so that it's easy for you to
            transfer from app to app.
            *Read through this file and modify the variables as appropriate.*

            ''')),
            dcc.Markdown(
                s('''
            #### Redeploy your app

            Your app should now have a Plotly Enterprise login screen.
            You can manage the permissions of the app in your list of files
            at `https://<your-plotly-domain>/organize`.
            '''))
        ]

    elif chapter == 'system':
        return [
            dcc.Markdown(
                s('''
            In some cases you may need to install and configure system
            dependencies. Examples include installing and configuring
            database drivers or the Java JRE environment.
            Plotly Enterprise supports these actions through an
            `apt-packages` file and a `predeploy` script.

            #### Install Apt Packages

            In the root of your application folder create a file called
            `apt-packages`. Here you may specify apt packages to be
            installed with one package per line. For example to install
            the ODBC driver we could include an `apt-packages` file that
            looks like:

            ''')),
            dcc.SyntaxHighlighter(s('''unixodbc
            unixodbc-dev
            '''),
                                  customStyle=styles.code_container,
                                  language="text"),
            dcc.Markdown(
                s('''

            #### Configure System Dependencies

            You may include a pre-deploy script that executes in
            your Dash App's environment. For the case of adding an
            ODBC driver we need to add ODBC initialization files into
            the correct systems paths. To do so we include the ODBC
            initialization files in the application folder and then
            copy them into system paths in the pre-deploy script.

            ##### Add A Pre-Deploy Script
            Let's generate a file to do this. Note that the file can
            have any name as we must specify the name in an application
            configuration file `app.json`.
            For the purposes of this example we assume we have
            named it `setup_pyodbc` and installed it in the root of our
            application folder.

            ''')),
            dcc.SyntaxHighlighter(s('''cp /app/odbc.ini /etc/odbc.ini
            cp /app/odbcinst.ini /etc/odbcinst.ini
            '''),
                                  customStyle=styles.code_container,
                                  language="text"),
            dcc.Markdown(
                s('''

            ##### Run Pre-Deploy Script Using `app.json`

            Next we must instruct Plotly Enterprise to run our `setup_pyodbc`
            file by adding a JSON configuration file named `app.json`
            into the root of our application folder.

            ''')),
            dcc.SyntaxHighlighter(s('''{
            \t"scripts": {
            \t\t"dokku": {
            \t\t\t"predeploy": "/app/setup_pyodbc"
            \t\t}
            \t}
            }
            '''),
                                  customStyle=styles.code_container,
                                  language='json'),
            dcc.Markdown(
                s('''
            ***

            Now when the application is deployed it will install the apt
            packages specified in `apt-packages` and run the setup file
            specified in `app.json`. In this case it allows us to install
            and then configure the ODBC driver.

            To see this example code in action
            [check out our ODBC example](https://github.com/plotly/dash-on-premise-sample-app/pull/3#issue-144272510)
             On-Premise application.
            '''))
        ]

    elif chapter == 'troubleshooting':
        return [
            dcc.Markdown(
                s('''
            If you encounter any issues deploying your app you can email
            `[email protected]`. It is helpful to include any error
            messages you encounter as well as available logs. See below on how
            to obtain Dash app logs as well as the Plotly Enterprise support
            bundle.

            #### Dash App Logs

            To view the logs for a specific Dash app run the following command
            in your terminal:

            ```
            ssh dokku@<your-dash-domain> logs <your-app-name> --num -1
            ```

            This will work for any app you have permission on, and uses the
            same mechanism as pushing the app via ssh.

            **Options**
            - `--num`, `-n`: The number of lines to display. By default, 100 lines are displayed.
               Set to -1 to display _all_ of the logs. Note that we only store logs from the latest app deploy.
            - `--tail`, `-t`: Continuously stream the logs.
            - `--quiet`, `-q`: Display the raw logs without colors, times, and names.
            ''')),
            dcc.Markdown(
                s('''
            #### Enterprise Support Bundle

            If you're requested to send the full support bundle you can
            download this from your Plotly Enterprise Server Manager
            (e.g. `https://<your.plotly.domain>:8800`). Please note you
            will need admin permissions to access the Server Manager.
            Navigate to the Server Manager and then select the Support tab.
            There you will see the option to download the support bundle.
            '''))
        ]
Пример #12
0
    'upload-datafile':
    tools.load_example('tutorial/examples/core_components/upload-datafile.py'),
    'upload-gallery':
    tools.load_example('tutorial/examples/core_components/upload-gallery.py'),
    'upload-image':
    tools.load_example('tutorial/examples/core_components/upload-image.py'),
}

# Dropdown
Dropdown = html.Div(children=[
    html.H1('Dropdown Examples and Reference'),
    html.Hr(),
    html.H3('Default Dropdown'),
    html.P("An example of a default dropdown without \
            any extra properties."),
    dcc.SyntaxHighlighter(examples['dropdown'][0],
                          customStyle=styles.code_container),
    html.Div(examples['dropdown'][1],
             className='example-container',
             style={'overflow-x': 'initial'}),
    html.Hr(),
    html.H3('Multi-Value Dropdown'),
    dcc.Markdown(
        "A dropdown component with the `multi` property set to `True` \
                  will allow the user to select more than one value \
                  at a time."),
    ComponentBlock('''import dash_core_components as dcc

dcc.Dropdown(
    options=[
        {'label': 'New York City', 'value': 'NYC'},
        {'label': 'Montreal', 'value': 'MTL'},
Пример #13
0
    # 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 {}.
    '''.replace('    ', '').format(daq.__version__)
)

daq_install_instructions = dcc.SyntaxHighlighter('''>>> import dash_daq as daq
    >>> print(daq.__version__)
    {}'''.replace('    ', '').format(daq.__version__),
    customStyle=styles.code_container)


dash_daq_components = {
    'BooleanSwitch': {
        'description': '''A switch component that toggles between on \
        and off.''',
        'props': {
            'on': True
        }
    },
    'ColorPicker': {
        'description': '''A color picker.''',
        'props': {
            'label': '\"colorPicker\"'
Пример #14
0
        'tutorial/examples/canvas_101.py',
        'tutorial/examples/canvas_image.py',
        'tutorial/examples/canvas_color.py',
        'tutorial/examples/canvas_annotations.py',
        'tutorial/examples/canvas_copy_annotations.py',
        'tutorial/examples/canvas_simple_segmentation.py',
    ]]

layout = html.Div([
    dcc.Markdown(dedent('''\
    ## Introduction to dash-canvas

    ''')),

    dcc.SyntaxHighlighter(
        '''pip install dash-canvas=={}'''.format(dash_canvas.__version__),
        customStyle=styles.code_container
    ),

    dcc.Markdown(dedent('''
    ``dash-canvas`` is a module for image annotation and image processing
    using Dash. It provides both the ``DashCanvas`` object for drawing
    and annotations on images, and a set of utility functions to process
    images using the annotations.

    ``dash-canvas`` can be used in various fields in which user
    interaction with images is required, such as quality control in
    industry, identification and segmentation of cells or organs in life
    and medical sciences, quantification of phases in materials and
    geosciences, construction of training sets for machine learning, etc.

    ### DashCanvas: a canvas object for annotations
Пример #15
0
    Some of this functionality is customizable and extendable.

    ***

    ## Including custom CSS and JavaScript in your Dash app
    '''.replace('    ', '')),
    dcc.SyntaxHighlighter('''from dash import Dash

app = Dash()

# Append an externally hosted CSS stylesheet
my_css_url = "https://unpkg.com/[email protected]"
app.css.append_css({
    "external_url": my_css_url
})

# Append an externally hosted JS bundle
my_js_url = 'https://unkpg.com/some-npm-package.js'
app.scripts.append_script({
    "external_url": my_js_url
})''',
                          language='python',
                          customStyle={'borderLeft': 'thin solid lightgrey'}),
    dcc.Markdown('''
    Dash currently only supports loading CSS and JavaScript bundles
    that are externally hosted.

    ***

    ### Default Styles
Пример #16
0
 > expect to make a few more breaking changes to its API and
 > behavior within the next couple of months.
 > Once the community feels good about its API, we'll lock it down
 >  and we'll commit to reducing the frequency of breaking changes.
 > Please subscribe to [dash-table#207](https://github.com/plotly/dash-table/issues/207)
 > and the [CHANGELOG.md](https://github.com/plotly/dash-table/blob/master/CHANGELOG.md) to stay up-to-date with any breaking changes.
 >
 > So, check out DataTable and let us know what you think.
 > Or even better, share your DataTable Dash apps
 > on the [community forum](https://community.plot.ly/t/show-and-tell-community-thread/7554)!
 >
 > -- chriddyp
 ''')),
 Section('Quickstart', [
     dcc.SyntaxHighlighter('''pip install dash-table=={}'''.format(
         dash_table.__version__),
                           customStyle=styles.code_container),
     dcc.SyntaxHighlighter(examples['simple.py'][0],
                           language='python',
                           customStyle=styles.code_container),
     html.Div(examples['simple.py'][1], className='example-container'),
 ]),
 Section('Dash DataTable User Guide', [
     Chapter(
         'Part 1. Sizing', '/datatable/sizing', '''
         All about sizing the DataTable. Examples include:
         - Setting the width and the height of the table
         - Responsive table design
         - Setting the widths of individual columns
         - Handling long text
         - Fixing rows and columns
Пример #17
0
    dcc.SyntaxHighlighter('''import datetime

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly
from dash.dependencies import Input, Output
    
# pip install pyorbital
from pyorbital.orbital import Orbital
satellite = Orbital('TERRA')

app = dash.Dash(__name__)
app.layout = html.Div(
    html.Div([
        html.H4('TERRA Satellite Live Feed'),
        html.Div(id='live-update-text'),
        dcc.Graph(id='live-update-graph'),
        dcc.Interval(
            id='interval-component',
            interval=1*1000, # in milliseconds
            n_intervals=0
        )
    ])
)


@app.callback(Output('live-update-text', 'children'),
              [Input('interval-component', 'n_intervals')])
def update_metrics(n):
    lon, lat, alt = satellite.get_lonlatalt(datetime.datetime.now())
    style = {'padding': '5px', 'fontSize': '16px'}
    return [
        html.Span('Longitude: {0:.2f}'.format(lon), style=style),
        html.Span('Latitude: {0:.2f}'.format(lat), style=style),
        html.Span('Altitude: {0:0.2f}'.format(alt), style=style)
    ]


# Multiple components can update everytime interval gets fired.
@app.callback(Output('live-update-graph', 'figure'),
              [Input('interval-component', 'n_intervals')])
def update_graph_live(n):
    satellite = Orbital('TERRA')
    data = {
        'time': [],
        'Latitude': [],
        'Longitude': [],
        'Altitude': []
    }

    # Collect some data
    for i in range(180):
        time = datetime.datetime.now() - datetime.timedelta(seconds=i*20)
        lon, lat, alt = satellite.get_lonlatalt(
            time
        )
        data['Longitude'].append(lon)
        data['Latitude'].append(lat)
        data['Altitude'].append(alt)
        data['time'].append(time)

    # Create the graph with subplots
    fig = plotly.tools.make_subplots(rows=2, cols=1, vertical_spacing=0.2)
    fig['layout']['margin'] = {
        'l': 30, 'r': 10, 'b': 30, 't': 10
    }
    fig['layout']['legend'] = {'x': 0, 'y': 1, 'xanchor': 'left'}

    fig.append_trace({
        'x': data['time'],
        'y': data['Altitude'],
        'name': 'Altitude',
        'mode': 'lines+markers',
        'type': 'scatter'
    }, 1, 1)
    fig.append_trace({
        'x': data['Longitude'],
        'y': data['Latitude'],
        'text': data['time'],
        'name': 'Longitude vs Latitude',
        'mode': 'lines+markers',
        'type': 'scatter'
    }, 2, 1)

    return fig


if __name__ == '__main__':
    app.run_server(debug=True)

''',
                          language='python',
                          customStyle={'borderLeft': 'thin solid lightgrey'}),
Пример #18
0
    example: tools.load_example('tutorial/examples/table/{}'.format(example))
    for example in ['dropdown_per_column.py', 'dropdown_per_row.py']
}

layout = html.Div([
    dcc.Markdown(
        dedent('''
    # DataTable Dropdowns

    The DataTable includes support for per-column and
    per-cell dropdowns. In future releases, this will
    be tightly integrated with a more formal typing system.

    For now, use the dropdown renderer as a way to limit the
    options available when editing the values with an editable table.

    ''')),
    section_title('DataTable with Per-Column Dropdowns'),
    dcc.SyntaxHighlighter(examples['dropdown_per_column.py'][0],
                          language='python',
                          customStyle=styles.code_container),
    html.Div(examples['dropdown_per_column.py'][1],
             className='example-container'),
    section_title('DataTable with Per-Row Dropdowns'),
    dcc.SyntaxHighlighter(examples['dropdown_per_row.py'][0],
                          language='python',
                          customStyle=styles.code_container),
    html.Div(examples['dropdown_per_row.py'][1],
             className='example-container'),
])
Пример #19
0
    three files in that folder:
    ```
    - app.py
    - assets/
        |-- typography.css
        |-- header.css
        |-- custom-script.js


    ```

    `app.py`

    ''')),
    dcc.SyntaxHighlighter(examples['local-css'][0],
                          language='python',
                          customStyle=styles.code_container),
    html.Hr(),
    html.Div(dcc.Markdown('`typography.css`'), style={'paddingTop': 20}),
    dcc.SyntaxHighlighter(s('''body {
    font-family: sans-serif;
}
h1, h2, h3, h4, h5, h6 {
    color: hotpink
}
        '''),
                          language='css',
                          customStyle=styles.code_container),
    html.Hr(),
    html.Div(dcc.Markdown('`header.css`'), style={'paddingTop': 20}),
    dcc.SyntaxHighlighter(s('''.app-header {
Пример #20
0
    html.H1('Dash Core Components'),
    dcc.Markdown('''
        Dash ships with supercharged components for interactive user interfaces.
        A core set of components, written and maintained by the Dash team,
        is available in the `dash-core-components` library.

        The source is on GitHub at [plotly/dash-core-components](https://github.com/plotly/dash-core-components).
    '''.replace('    ', '')),
    html.Hr(),
    html.H3('Dropdown'),
    dcc.SyntaxHighlighter('''import dash_core_components as dcc

dcc.Dropdown(
    options=[
        {'label': 'New York City', 'value': 'NYC'},
        {'label': 'Montréal', 'value': 'MTL'},
        {'label': 'San Francisco', 'value': 'SF'}
    ],
    value='MTL'
)''',
                          language='python',
                          customStyle=styles.code_container),
    dcc.Dropdown(options=[{
        'label': 'New York City',
        'value': 'NYC'
    }, {
        'label': 'Montréal',
        'value': 'MTL'
    }, {
        'label': 'San Francisco',
        'value': 'SF'
    }],
Пример #21
0
    for example in ['virtualization.py']
}

layout = html.Div([
    dcc.Markdown(
        dedent("""
        # Virtualization
        
        In addition to pagination, `DataTable` also has virtualization capabilities 
        for viewing large datasets. Virtualization saves browser resources while 
        still permitting the user to scroll through the entire dataset. It achieves this
        by only a rendering a subset of the data at any instant.
        
        The virtualiztion backend makes a few assumptions about the style of
        your `DataTable` which must be adhered to in order to ensure that the 
        table scrolls smoothly.
        
        - the width of the columns is fixed
        - the height of the rows is always the same
        - runtime styling changes will not affect width and height compared to
        the table's first rendering
        
        The example below prevents runtime style changes by fixing the column
        widths and setting the white-space CSS property in the cells to normal.
        """)),
    dcc.SyntaxHighlighter(examples['virtualization.py'][0],
                          language='python',
                          customStyle=styles.code_container),
    html.Div(examples['virtualization.py'][1], className='example-container'),
])
Пример #22
0
easy git-based deployment, automatic URL namespacing,
built-in SSL support, LDAP authentication, and more.
[Learn more about Dash Deployment Server](https://plot.ly/dash/pricing) or 
[get in touch to start a trial](https://plotly.typeform.com/to/rkO85m).

For existing customers, see the [Dash Deployment Server Documentation](/dash-deployment-server).

### Dash and Flask

Dash apps are web applications. Dash uses Flask as the web framework.
The underlying Flask app is available at `app.server`, that is:
'''),
    dcc.SyntaxHighlighter('''import dash

app = dash.Dash(__name__)

server = app.server # the Flask app
''',
                          language='python',
                          customStyle=styles.code_container),
    dcc.Markdown('''
You can also pass your own flask app instance into Dash:
'''),
    dcc.SyntaxHighlighter('''import flask

server = flask.Flask(__name__)
app = dash.Dash(__name__, server=server)
''',
                          language='python',
                          customStyle=styles.code_container),
    dcc.Markdown('''
By exposing this `server` variable, you can deploy Dash apps like you would
Пример #23
0
    ]
]

layout = html.Div(children=[
    dcc.Markdown('''
    ## Interactivity with Callbacks

    The heart and soul of Dash is providing an easy way to bind Python
    callbacks to web interfaces.

    With Dash's callback decorators, you can update certain components
    when other components change values. Here's a practical example.
    View the interactive app below the code.

    '''.replace('    ', '')),
    dcc.SyntaxHighlighter(
        examples[0][0], language='python', customStyle=styles.code_container),
    html.Div('This code will generate an app like this:'),
    html.Div(examples[0][1], className='example-container')
])

layout.children.extend([
    dcc.Markdown('''
## Multiple Inputs

Let's extend this example by including
a secondary input element that controls
which variable we should plot.

Dash apps are "reactive" which means that
whenever values change in the front-end,
the callback functions will get called
Пример #24
0
    def test_gallery(self):
        app = dash.Dash(__name__)

        app.layout = html.Div([
            html.Div(id='waitfor'),
            html.Label('Upload'),
            dcc.Upload(),
            html.Label('Horizontal Tabs'),
            dcc.Tabs(
                id="tabs",
                children=[
                    dcc.Tab(label='Tab one',
                            className='test',
                            style={'border': '1px solid magenta'},
                            children=[html.Div(['Test'])]),
                    dcc.Tab(label='Tab two',
                            children=[
                                html.Div([
                                    html.H1("This is the content in tab 2"),
                                    html.P("A graph here would be nice!")
                                ])
                            ],
                            id='tab-one'),
                    dcc.Tab(label='Tab three',
                            children=[
                                html.Div([
                                    html.H1("This is the content in tab 3"),
                                ])
                            ]),
                ],
                style={'fontFamily': 'system-ui'},
                content_style={
                    'border': '1px solid #d6d6d6',
                    'padding': '44px'
                },
                parent_style={
                    'maxWidth': '1000px',
                    'margin': '0 auto'
                }),
            html.Label('Vertical Tabs'),
            dcc.Tabs(
                id="tabs1",
                vertical=True,
                children=[
                    dcc.Tab(label='Tab one', children=[html.Div(['Test'])]),
                    dcc.Tab(label='Tab two',
                            children=[
                                html.Div([
                                    html.H1("This is the content in tab 2"),
                                    html.P("A graph here would be nice!")
                                ])
                            ]),
                    dcc.Tab(label='Tab three',
                            children=[
                                html.Div([
                                    html.H1("This is the content in tab 3"),
                                ])
                            ]),
                ]),
            html.Label('Dropdown'),
            dcc.Dropdown(options=[{
                'label': 'New York City',
                'value': 'NYC'
            }, {
                'label': u'Montréal',
                'value': 'MTL'
            }, {
                'label': 'San Francisco',
                'value': 'SF'
            }, {
                'label': u'北京',
                'value': u'北京'
            }],
                         value='MTL',
                         id='dropdown'),
            html.Label('Multi-Select Dropdown'),
            dcc.Dropdown(options=[{
                'label': 'New York City',
                'value': 'NYC'
            }, {
                'label': u'Montréal',
                'value': 'MTL'
            }, {
                'label': 'San Francisco',
                'value': 'SF'
            }, {
                'label': u'北京',
                'value': u'北京'
            }],
                         value=['MTL', 'SF'],
                         multi=True),
            html.Label('Radio Items'),
            dcc.RadioItems(options=[{
                'label': 'New York City',
                'value': 'NYC'
            }, {
                'label': u'Montréal',
                'value': 'MTL'
            }, {
                'label': 'San Francisco',
                'value': 'SF'
            }, {
                'label': u'北京',
                'value': u'北京'
            }],
                           value='MTL'),
            html.Label('Checkboxes'),
            dcc.Checklist(options=[{
                'label': 'New York City',
                'value': 'NYC'
            }, {
                'label': u'Montréal',
                'value': 'MTL'
            }, {
                'label': 'San Francisco',
                'value': 'SF'
            }, {
                'label': u'北京',
                'value': u'北京'
            }],
                          values=['MTL', 'SF']),
            html.Label('Text Input'),
            dcc.Input(value='',
                      placeholder='type here',
                      type='text',
                      id='textinput'),
            html.Label('Disabled Text Input'),
            dcc.Input(value='disabled',
                      type='text',
                      id='disabled-textinput',
                      disabled=True),
            html.Label('Slider'),
            dcc.Slider(
                min=0,
                max=9,
                marks={
                    i: 'Label {}'.format(i) if i == 1 else str(i)
                    for i in range(1, 6)
                },
                value=5,
            ),
            html.Label('Graph'),
            dcc.Graph(id='graph',
                      figure={
                          'data': [{
                              'x': [1, 2, 3],
                              'y': [4, 1, 4]
                          }],
                          'layout': {
                              'title': u'北京'
                          }
                      }),
            html.Label('DatePickerSingle'),
            dcc.DatePickerSingle(id='date-picker-single',
                                 date=datetime(1997, 5, 10)),
            html.Label('DatePickerRange'),
            dcc.DatePickerRange(id='date-picker-range',
                                start_date=datetime(1997, 5, 3),
                                end_date_placeholder_text='Select a date!'),
            html.Label('TextArea'),
            dcc.Textarea(placeholder='Enter a value... 北京',
                         style={'width': '100%'}),
            html.Label('Markdown'),
            dcc.Markdown('''
                #### Dash and Markdown

                Dash supports [Markdown](http://commonmark.org/help).

                Markdown is a simple way to write and format text.
                It includes a syntax for things like **bold text** and *italics*,
                [links](http://commonmark.org/help), inline `code` snippets, lists,
                quotes, and more.

                北京
            '''.replace('    ', '')),
            dcc.Markdown(['# Line one', '## Line two']),
            dcc.Markdown(),
            dcc.SyntaxHighlighter(dedent('''import python
                print(3)'''),
                                  language='python'),
            dcc.SyntaxHighlighter(['import python', 'print(3)'],
                                  language='python'),
            dcc.SyntaxHighlighter()
        ])
        self.startServer(app)

        self.wait_for_element_by_css_selector('#waitfor')

        self.snapshot('gallery')

        self.driver.find_element_by_css_selector(
            '#dropdown .Select-input input').send_keys(u'北')
        self.snapshot('gallery - chinese character')

        text_input = self.driver.find_element_by_id('textinput')
        disabled_text_input = self.driver.find_element_by_id(
            'disabled-textinput')
        text_input.send_keys('HODOR')

        # It seems selenium errors when send(ing)_keys on a disabled element.
        # In case this changes we try anyway and catch the particular
        # exception. In any case Percy will snapshot the disabled input style
        # so we are not totally dependent on the send_keys behaviour for
        # testing disabled state.
        try:
            disabled_text_input.send_keys('RODOH')
        except InvalidElementStateException:
            pass

        self.snapshot('gallery - text input')
    'rangeslider-nonlinear': tools.load_example('tutorial/examples/core_components/rangeslider_nonlinear.py'),
    'upload-image':  tools.load_example('tutorial/examples/core_components/upload-image.py'),
    'upload-datafile':  tools.load_example('tutorial/examples/core_components/upload-datafile.py'),
    'upload-gallery':  tools.load_example('tutorial/examples/core_components/upload-gallery.py'),
}


# Dropdown
Dropdown = html.Div(children=[
    html.H1('Dropdown Examples and Reference'),
    html.Hr(),
    html.H3('Default Dropdown'),
    html.P("An example of a default dropdown without \
            any extra properties."),
    dcc.SyntaxHighlighter(
        examples['dropdown'][0],
        customStyle=styles.code_container
    ),
    html.Div(
        examples['dropdown'][1],
        className='example-container',
        style={'overflow-x': 'initial'}
    ),

    html.Hr(),
    html.H3('Multi-Value Dropdown'),
    dcc.Markdown("A dropdown component with the `multi` property set to `True` \
                  will allow the user to select more than one value \
                  at a time."),
    ComponentBlock('''import dash_core_components as dcc

dcc.Dropdown(
Пример #26
0
def model_layout(model_name):
    """Create a Dash layout for a provided model.

    Args:
      model_name: an instance of an AbstractModel subclass

    Returns:
      Dash layout

    """

    # dict to hold layouts for each section
    layouts = OrderedDict()

    # instantiate model from name
    model = DEFAULT_MODEL_DICT[model_name]

    model_title = html.Div(className='row', children=[
        html.H3(model.title),
    ])

    # TODO: costly, should just construct subgraph directly?
    g = Graph()
    subgraph = nx.ego_graph(g.get_networkx_graph(), model, undirected=True)
    options = AESTHETICS['global_options']
    if "arrows" in options["edges"]:
        options["edges"]["arrows"] = "to"
    layouts['Graph'] = html.Div(GraphComponent(
        id="model_graph",
        graph=graph_conversion(subgraph),
        options=AESTHETICS['global_options']),
                                style={
                                    'width': '100%',
                                    'height': '300px'
                                })

    if model.categories:
        tags = html.Ul(className="tags",
                       children=[
                           html.Li(tag, className="tag")
                           for tag in model.categories
                       ])
        layouts['Tags'] = tags

    if model.references:
        references = html.Div([
            dcc.Markdown(references_to_markdown(ref))
            for ref in model.references
        ])

        layouts['References'] = references

    symbols = html.Div(children=[
        html.Div(className='row',
                 children=[
                     html.Div(className='two columns', children=[str(symbol)]),
                     html.Div(
                         className='ten columns',
                         children=[
                             dcc.Link(
                                 DEFAULT_SYMBOLS[prop_name].display_names[0],
                                 href='/property/{}'.format(prop_name))
                         ])
                 ]) for symbol, prop_name in model.symbol_property_map.items()
    ])

    layouts['Symbols'] = symbols

    layouts['Description'] = dcc.Markdown(model.description)

    if model.validate_from_preset_test():
        sample_data_header = html.Div(
            className='row',
            children=[
                html.Div(className='five columns',
                         style={'text-align': 'center'},
                         children=[html.H4('Input(s)')]),
                html.Div(className='two columns',
                         style={'text-align': 'center'},
                         children=[html.H4('->')]),
                html.Div(className='five columns',
                         style={'text-align': 'center'},
                         children=[html.H4('Output(s)')])
            ])

        layouts['Sample Code'] = html.Div([
            dcc.Markdown(
                "Propnet models can be called directly, with propnet acting "
                "as a library of tested materials science models. Sample code for this "
                "model is as follows:"),
            dcc.SyntaxHighlighter(model.example_code)
        ])

    sublayouts = []
    for title, layout in layouts.items():
        sublayouts.append(html.H6(title))
        sublayouts.append(layout)

    return html.Div([
        model_title,
        html.Br(),
        *sublayouts,
        html.Br(),
        #dcc.Link('< Back to Models', href='/model'),
        #html.Br(),
        dcc.Link('< Back', href='/explore')
    ])
Пример #27
0
  ***'''),
    html.H2('''
    Installation
    ''', id='installation'),
    dcc.Markdown('''

    In your terminal, install several dash libraries.
    These libraries are under active development,
    so install and upgrade frequently.
    Python 2 and 3 are supported.'''.replace('    ', '')),
    dcc.SyntaxHighlighter('''pip install dash=={}  # The core dash backend
        pip install dash-renderer=={}  # The dash front-end
        pip install dash-html-components=={}  # HTML components
        pip install dash-core-components=={}  # Supercharged components
        pip install plotly=={}  # Plotly graphing library used in examples
    '''.replace('    ', '').format(dash.__version__, dash_renderer.__version__,
                                   html.__version__, dcc.__version__,
                                   plotly.__version__),
                          customStyle=styles.code_container),
    html.H2('''
    Interactivity
    ''', id='interactivity'),
    dcc.Markdown('''

        The [first part](/dash/getting-started) of this tutorial
        covered the `layout` of Dash apps. The `layout` of a Dash app
        describes what the app looks like.
        It is a hierarchical tree of components.
        The `dash_html_components` library provides classes for all of the HTML
        tags and the keyword arguments describe the HTML attributes like `style`,
Пример #28
0
    dcc.SyntaxHighlighter('''import dash
import dash_core_components as dcc
import dash_html_components as html

print(dcc.__version__) # 0.6.0 or above is required

app = dash.Dash()

app.layout = html.Div([
    # represents the URL bar, doesn't render anything
    dcc.Location(id='url', refresh=False),

    dcc.Link('Navigate to "/"', href='/'),
    html.Br(),
    dcc.Link('Navigate to "/page-2"', href='/page-2'),

    # content will be rendered in this element
    html.Div(id='page-content')
])


@app.callback(dash.dependencies.Output('page-content', 'children'),
              [dash.dependencies.Input('url', 'pathname')])
def display_page(pathname):
    return html.Div([
        html.H3('You are on page {}'.format(pathname))
    ])


app.css.append_css({
    'external_url': 'https://codepen.io/chriddyp/pen/bWLwgP.css'
})


if __name__ == '__main__':
    app.run_server(debug=True)
''',
                          language='python',
                          customStyle=styles.code_container),
Пример #29
0
    Logging in through Basic Auth looks like this:
    '''.replace('    ', '')),
    html.Img(
        src=
        'https://github.com/plotly/dash-docs/raw/master/images/basic-auth.gif',
        alt='Dash Basic Auth Example',
        style={
            'width': '100%',
            'border': 'thin lightgrey solid',
            'border-radius': '4px'
        }),
    dcc.Markdown('''
    Installation:
    '''.replace('    ', '')),
    dcc.SyntaxHighlighter('''pip install dash=={}
        pip install dash-auth=={}'''.replace('    ', '').format(
        dash.__version__, dash_auth.__version__),
                          customStyle=styles.code_container),
    dcc.Markdown('''
    Example Code:
    '''.replace('    ', '')),
    dcc.SyntaxHighlighter('''import dash
import dash_auth
import dash_core_components as dcc
import dash_html_components as html
import plotly

# Keep this out of source code repository - save in a file or a database
VALID_USERNAME_PASSWORD_PAIRS = [
    ['hello', 'world']
]
Пример #30
0
                  dcc.SyntaxHighlighter(
                      dedent('''
     nodes = [
         {
             'data': {'id': short, 'label': label}, 
             'position': {'x': 20*lat, 'y': -20*long}
         }
         for short, label, long, lat in (
             ('la', 'Los Angeles', 34.03, -118.25),
             ('nyc', 'New York', 40.71, -74),
             ('to', 'Toronto', 43.65, -79.38),
             ('mtl', 'Montreal', 45.50, -73.57),
             ('van', 'Vancouver', 49.28, -123.12),
             ('chi', 'Chicago', 41.88, -87.63),
             ('bos', 'Boston', 42.36, -71.06),
             ('hou', 'Houston', 29.76, -95.37)
         )
     ]
 
     edges = [
         {'data': {'source': source, 'target': target}}
         for source, target in (
             ('van', 'la'),
             ('la', 'chi'),
             ('hou', 'chi'),
             ('to', 'mtl'),
             ('mtl', 'bos'),
             ('nyc', 'boston'),
             ('to', 'hou'),
             ('to', 'nyc'),
             ('la', 'nyc'),
             ('nyc', 'bos')
         )
     ]
 
     elements = nodes + edges
     '''))