当接收到新的JSON数据时,如何将新行附加到“dbc.Table.from_dataframe”破折号组件?

2024-05-14 00:07:20 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是一个示例仪表板,它使用plotly dash发布和订阅MQTT消息。在JSON中接收到来自特定主题的消息后,将创建一个数据帧,并将其填充到具有id = gw_tabledbc.Table.from_dataframe。要求是当接收到新的JSON数据时,数据表需要附加一个新行,在下面的脚本中,它用新接收的数据重新填充第一行

阅读文档和其他类似问题时,我尝试了dcc.store,但没有成功

app.py

import dash
import dash_html_components as html
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import flask
from dash.dependencies import Input, Output, State
import json
import dash_mqtt
import pandas as pd

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

server = flask.Flask(__name__)
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.config.suppress_callback_exceptions = True


TEST_SERVER = 'localhost'
TEST_SERVER_PORT = 1884
#TEST_SERVER_PATH = 'websockets'
MQTT_TOPIC_Registration = 'posttopic'

MQTT_TOPIC_Registration_Response = '#'

app.layout = html.Div([

                        
                        dcc.Tabs([
                           dcc.Tab(id = 'gw_id_tab', label='Registration', children = [
                                html.Div([ 
                                    dash_mqtt.DashMqtt(
                                                            id='mqtt',
                                                            broker_url=TEST_SERVER,
                                                            broker_port = TEST_SERVER_PORT,
                                                            #broker_path = TEST_SERVER_PATH,
                                                            topics=[MQTT_TOPIC_Registration, MQTT_TOPIC_Registration_Response]
                                                            ),
 
                           
                                        html.Div([
                                                    html.Button('Register', id='post-val', n_clicks=0)
                                                    
                                                ],style = {'marginTop': 50, 'margin-left' : '600px'}),
                                        
                                        html.Br(),
                                        
                                        html.Div(
                                            
                                            
                                            id= 'gw_table'
                                            
                                            
                                            
                                            ),
                                        html.Div([
                                            dcc.ConfirmDialog(
                                                                id='confirm',
                                                                message='Are you sure you want to continue ?',
                                                            )]),
                          
                                                      

                          
                                ],style={'width':'100%', 'margin': 20})

                            ]),
                            
                            
                            dcc.Tab(label='TAB2', children = [
                                       html.Div([
                                            
                                              html.H3('Tab content 2')
                                            
                                            ])
                                
                                ])                            

    ]),
    html.Div(id='tabs-content')
    
])




@app.callback(
    Output('confirm', 'displayed'),
    [Input('post-val', 'n_clicks')]
    
    )


def display_confirm(clicked):
    
    if clicked:
        return True
    return False


   
@app.callback(
    Output('gw_table','children'),
    [Input('mqtt', 'incoming')]
    )

def update_table(incoming_message):
    if (incoming_message):
        
        gw_json =  incoming_message['payload']
        gw_table = pd.DataFrame([pd.read_json(gw_json,  typ='series')])
        return dbc.Table.from_dataframe(gw_table)
        
    else:
        return dash.no_update
        
        

if __name__ == '__main__':
    app.run_server(host='0.0.0.0',port=8050,debug=True)

那么,当接收到新的JSON数据时,如何向dbc.Table.from_dataframe追加新行


Tags: 数据testimportdividappserverhtml
1条回答
网友
1楼 · 发布于 2024-05-14 00:07:20

通过检查使用dbc.Table.from_dataframe创建的表对象,我们可以看到它的children属性加载了dataframe中必要的行和头元素。因此,如果您已经从数据帧加载了一个表(如表1),并且您希望添加新的JSON数据,然后将其转换为数据帧(如df_2),并将其与表1的数据一起添加,那么如下所示:

df_2 = pd.read_json(new_json)
table_2 = dbc.Table.from_dataframe(df_2)
table_3 = dbc.Table()
table_3.children = table_1.children+table_2.children[1:] # remove the first element from table_2's children as this contains its header and is not needed
table_1 = table_3 # to override table_1 with the new data

当然,这段代码假设新的JSON的结构与您希望附加到的原始数据的结构相同,所以要小心。如果希望保留表_1中的其他属性,如styleclassName,则只需将表_3的属性指定给表_1的属性,即可在新表中保留该属性

编辑: 现在还不清楚你是打算刷新整个应用程序来获取这个新的JSON,还是在不刷新的情况下获取它。我现在假设后者,在这种情况下,您应该使用dcc.interval组件来刷新您的应用程序,而不必手动单击刷新,因此您现在可以在此时间间隔上创建回调,从原始表中获取数据,并使用上面提到的方法将新的JSON添加到其中

相关问题 更多 >