`row_update` in `dash_table.DataTable`

I used ‘active_cell’ with ‘data_timestamp’. I also used that to make a call back to update a database table.

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


app = dash.Dash()
app.config.suppress_callback_exceptions = False
app.scripts.config.serve_locally = True
app.css.config.serve_locally = True

df = pd.DataFrame([[1, 2], [3, 4], [5, 6], [7, 8]], columns=["A", "B"])
           
app.layout = html.Div([
    html.H1(
        children='Sample Table - Shows how to identify modified Row',
        style={
            'textAlign': 'center'
        }
    ),

                   
    dash_table.DataTable(
                id='table-editing-simple',
                columns=[
                    {"name": "A", "id": "A", "editable": False},
                    {"name": "B", "id": "B", "editable": True}],
                data = df.to_dict("rows"),
                editable = True
                ),
    html.Div(
            html.H5(
                id='table-action-outputs',
                children='',
                style={'textAlign': 'left'}),
            style={'width': '100%', 'display': 'inline-block', 'float': 'left'},
            ),

])



@app.callback(Output('table-action-outputs', 'children'),
              [Input('table-editing-simple', 'data_timestamp'),
              Input('table-editing-simple', 'active_cell'),
              Input('table-editing-simple', 'data')])
def update_database(time_updated, cell_coordinates, table_data):
    time_updated = round(time_updated / 1000)
    time_now = round(time.time()) - 2
    if (time_updated) >= time_now:
       db_response = str(time_updated) + " " +  str(time_now)
       str_return = "Data timestamp:" + str(time_updated) 
       str_return2 = ".  Did you update this row? " + str(table_data[cell_coordinates[0]])
       sql_query = "UPDATE table SET B = '{table_data[cell_coordinates[0]][cell_coordinates[1]]}', MODIFIED_DATE = {time_updated} WHERE A = '{table_data[cell_coordinates[0]][cell_coordinates[0]]}'"
       db_response = f".  Sample DB SQL Update statement: {sql_query}"  
    else:
       time_round = round(time.time())
       str_return = "No time match. " + str(type(time_updated)) + " is the Dash updated time which does not match this server time:  " + str(time_round) + "\n"
       str_return2 = ".  No matching record found due to time issue.\n"
       db_response = ".  No DB update due to time gap issue.\n"
    return str_return, str_return2, db_response

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

1 Like