Как вы обновляете данные в графически? - PullRequest
0 голосов
/ 30 января 2020

Я хотел бы показать кадр данных, который загружается только после нажатия кнопки «Отправить».
В настоящее время мое приложение ожидает кадр данных с самого начала:

Вот app.py

import dash_daq as daq
import plotly.graph_objects as go
import dash_core_components as dcc
import dash_html_components as html
import datetime as dt
import dash_table

from . import utils
from .server import app, server

from .callbacks import (search)

def article_search():
    return html.Div(
        [
            # Value we searc in the text
            html.Div(dcc.Input(id='input-box', type='text', value = 'Bank')),
            # Dropdown
            html.Div([
                dcc.Dropdown(
                    id='demo-dropdown',
                    options=[
                        {'label': 'truco1', 'value': 'truco1'},
                        {'label': 'truco2', 'value': 'truco2'}
                    ],
                    value='truco1'
                ),
                html.Div(id='dd-output-container')
            ]),
            # Date picker, to be change to a range selector
            html.Div([
                dcc.DatePickerRange(
                    id='my-date-picker-range',
                    min_date_allowed=dt.datetime(1995, 8, 5),
                    max_date_allowed=dt.datetime.today(),
                    initial_visible_month=dt.datetime(2017, 8, 5),
                    end_date=dt.datetime.today()
                ),
                html.Div(id='output-container-date-picker-range')
            ]),
            # Submit button
            html.Button(children = 'Submit', id='submit-button',),
            # articles
            html.Div(id='output-container-button',
                     children='Enter a value and press submit'),
            html.Div(
                id='articles',
                children='Matching articles',
            ),
            html.Div(id='computed-table')
            )
        ]
    )


app.layout = html.Div(
    [
        # empty Div to trigger javascript file for graph resizing
        html.Div(id="output-clientside"),
        # Header
        header(),
        dcc.Tabs(
            [
                dcc.Tab(
                    label='Search article',
                    value='search',
                    children=article_search()
                )
            ]
        )
    ]
)

А вот обратный вызов, search.py:

from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import datetime as dt
import pandas as pd
import plotly.graph_objects as go
import pickle

from ..server import app

PAGE_SIZE = 10

@app.callback(
    Output('computed-table', 'children'),
    [Input('submit-button', 'n_clicks'),
    Input('my-date-picker-range', 'start_date'),
    Input('my-date-picker-range', 'end_date'),
    Input('demo-dropdown', 'value')], 
    [State('input-box', 'value')])
def update_search(n_clicks, start_date, end_date, selection, word):
    f = pickle.load(open("dashboard/data-mm/truc.p", "rb"))
    articles = []
    print(type(start_date))
    start_date = dt.datetime.fromisoformat(start_date)
    end_date = dt.datetime.fromisoformat(end_date)

    for article in f:
        if word in article['headline']:
            if article['date'] is not None and article['date'] > start_date and article['date'] <end_date:
                articles.append(article)

    df = pd.DataFrame(articles)
    grouped = df.groupby(['date']).count()

    max_rows = 100
    return html.Table(
        # Header
        [html.Tr([html.Th(col) for col in df.columns])] +

        # Body
        [html.Tr([
            html.Td(df.iloc[i][col]) for col in df.columns
        ]) for i in range(min(len(df), max_rows))]
    )

И он возвращает меня:

introducir la descripción de la imagen aquí.

Сообщение об ошибке:

Объект был указан как children вместо компонента, строки или числа (или их списка). Проверьте свойство children, которое выглядит примерно так: {}

Но я бы хотел использовать dash_table.DataTable, кажется, он более интерактивный . Однако, когда я пытаюсь играть с ним, в search.py:

return html.Div([
    dash_table.DataTable(
        id='table',
        columns=[{"name": i, "id": i} for i in df.columns],
        data=df.head().to_dict("rows"),
        style_cell={'width': '300px',
        'height': '60px',
        'textAlign': 'left'})
    ])

И, в app.py, замените Div на id: на html .Div (id = 'computed-table') `, не показывает таблицу и отправляет мне обратно:

Objects are not valid as a React child (found: object with keys {/Finance/Banking}). If you meant to render a collection of children, use an array instead.
    in div (created by t)
    in t (created by t)
    in td (created by t)
    in t (created by t)
    in tr (created by t)
    in tbody (created by t)
    in table (created by t)
    in div (created by t)
    in div (created by t)
    in div (created by t)
    in div (created by t)
    in div (created by t)
    in t (created by t)
    in t (created by t)
    in t (created by t)
    in Suspense (created by t)
    in t (created by CheckedComponent)
    in CheckedComponent (created by TreeContainer)
    in UnconnectedComponentErrorBoundary (created by Connect(UnconnectedComponentErrorBoundary))
    in Connect(UnconnectedComponentErrorBoundary) (created by TreeContainer)
    in TreeContainer (created by Connect(TreeContainer))
    in Connect(TreeContainer) (created by TreeContainer)
    in div (created by u)
    in u (created by CheckedComponent)
    in CheckedComponent (created by TreeContainer)
    in UnconnectedComponentErrorBoundary (created by Connect(UnconnectedComponentErrorBoundary))
    in Connect(UnconnectedComponentErrorBoundary) (created by TreeContainer)
    in TreeContainer (created by Connect(TreeContainer))
    in Connect(TreeContainer) (created by TreeContainer)
    in div (created by u)
    in u (created by CheckedComponent)
    in CheckedComponent (created by TreeContainer)
    in UnconnectedComponentErrorBoundary (created by Connect(UnconnectedComponentErrorBoundary))
    in Connect(UnconnectedComponentErrorBoundary) (created by TreeContainer)
    in TreeContainer (created by Connect(TreeContainer))
    in Connect(TreeContainer) (created by TreeContainer)
    in div (created by u)
    in u (created by CheckedComponent)
    in CheckedComponent (created by TreeContainer)
    in UnconnectedComponentErrorBoundary (created by Connect(UnconnectedComponentErrorBoundary))
    in Connect(UnconnectedComponentErrorBoundary) (created by TreeContainer)
    in TreeContainer (created by Connect(TreeContainer))
    in Connect(TreeContainer) (created by TreeContainer)
    in ui (created by CheckedComponent)
    in CheckedComponent (created by TreeContainer)
    in UnconnectedComponentErrorBoundary (created by Connect(UnconnectedComponentErrorBoundary))
    in Connect(UnconnectedComponentErrorBoundary) (created by TreeContainer)
    in TreeContainer (created by Connect(TreeContainer))
    in Connect(TreeContainer) (created by TreeContainer)
    in div (created by t)
    in div (created by t)
    in t (created by CheckedComponent)
    in CheckedComponent (created by TreeContainer)
    in UnconnectedComponentErrorBoundary (created by Connect(UnconnectedComponentErrorBoundary))
    in Connect(UnconnectedComponentErrorBoundary) (created by TreeContainer)
    in TreeContainer (created by Connect(TreeContainer))
    in Connect(TreeContainer) (created by TreeContainer)
    in div (created by u)
    in u (created by CheckedComponent)
    in CheckedComponent (created by TreeContainer)
    in UnconnectedComponentErrorBoundary (created by Connect(UnconnectedComponentErrorBoundary))
    in Connect(UnconnectedComponentErrorBoundary) (created by TreeContainer)
    in TreeContainer (created by Connect(TreeContainer))
    in Connect(TreeContainer) (created by UnconnectedContainer)
    in div (created by UnconnectedGlobalErrorContainer)
    in div (created by GlobalErrorOverlay)
    in div (created by GlobalErrorOverlay)
    in GlobalErrorOverlay (created by DebugMenu)
    in div (created by DebugMenu)
    in DebugMenu (created by UnconnectedGlobalErrorContainer)
    in div (created by UnconnectedGlobalErrorContainer)
    in UnconnectedGlobalErrorContainer (created by Connect(UnconnectedGlobalErrorContainer))
    in Connect(UnconnectedGlobalErrorContainer) (created by UnconnectedContainer)
    in UnconnectedContainer (created by Connect(UnconnectedContainer))
    in Connect(UnconnectedContainer) (created by UnconnectedAppContainer)
    in UnconnectedAppContainer (created by Connect(UnconnectedAppContainer))
    in Connect(UnconnectedAppContainer) (created by AppProvider)
    in Provider (created by AppProvider)
    in AppProvider

Обновление

Я думаю, что проблема в том, что некоторые строки df есть пустые словари, и поэтому у меня появляется следующее сообщение об ошибке:

Objects are not valid as a React child (found: object with keys {}
...