通过回调更新Dash Datatable

时间:2019-11-22 21:56:05

标签: python plotly python-3.7 plotly-dash

我想基于一个间隔更新我的Dash data_table。它将运行,但是没有任何更新。我认为这并不难,但我显然缺少一些东西。这是我所拥有的:

import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import time
import pandas as pd

数据组件

def getData():
"""
Only can hit api every 6 seconds for 14 total items, 
which is relevant towards the Dash interval  
    """
        df = pd.DataFrame()
        for item in list:
            data  = *hit api*
            df = df.append(data)
            time.sleep(7)
        return df

破折号组件

app = dash.Dash(__name__)

# passing in just column names to avoid needlessly hitting API 
tblcols=[{'name': 'col1', 'id': 'col1'},
     {'name': 'col2', 'id': 'col2'}, 
     {'name': 'col3', 'id': 'col3'}      
     ]

app.layout = html.Div([
      html.H4('Dashboard Name'),
      dcc.Interval('graph-update',interval = 500000, n_intervals = 0),
      dash_table.DataTable(
              id = 'table',
          data = [{}],
          columns=tblcols )])

@app.callback(
        Output('table','data'),
        [Input('graph-update', 'n_intervals')]
        )
def updateTable(n):

     """
     calling the get data function
     """

     updated_data = getData()
     return updated_data.to_dict('records')

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

同样,它将运行并返回我通过的列标题,但是当我看到更新已在控制台““ POST / _dash-update-component HTTP / 1.1”“中运行时,没有任何变化

1 个答案:

答案 0 :(得分:0)

我认为问题在于您返回了一个空的dataframe。这是因为您使用df.append(data)而不是df = df.append(data)

这是一个简化且有效的代码(Dash v1.6.0):

import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import pandas as pd
import numpy as np

app = dash.Dash(__name__)

def getData():
    df = pd.DataFrame()
    for idx in range(10):
        data  = {'x': np.random.random(1)[0], 'y': np.random.random(1)[0]}
        df = df.append(data, ignore_index=True)
    return df.to_dict('records')

tblcols=[{'name': 'x', 'id': 'x'},
         {'name': 'y', 'id': 'y'}, ]

app.layout = html.Div([
      html.H4('Dashboard'),
      dcc.Interval('graph-update', interval = 1000, n_intervals = 0),
      dash_table.DataTable(
          id = 'table',
          data = getData(),
          columns=tblcols)])

@app.callback(
        dash.dependencies.Output('table','data'),
        [dash.dependencies.Input('graph-update', 'n_intervals')])
def updateTable(n):
     return getData()

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

enter image description here