page1.py
import ... .layout as layout
import dash
import pandas as pd
dash.register_page(__name__, path='/page_one') # I have an app.py which is running the app
df = pd.DataFrame({'A': [1, 2, 3, 4, 5],
'B': [6, 7, 8, 9, 10]})
df = df.reset_index()
layout = layout.update_page(df)
layout.py
import dash_bootstrap_components as dbc
from dash import dcc,html,Input, Output, callback
from dash import dash_table
import dash_daq as daq
def update_page(arg1):
layout = html.Div(children = [
dbc.Col(daq.NumericInput(
id='my-numeric-input-1',
min=0,
max=100,
value=0,
label='Update Table',
labelPosition='top',
style={"paddingBottom": 15}),)
,html.Br(),
dash_table.DataTable(
id='table',
data=arg1.to_dict('records'),
columns=[{"name": i, "id": i} for i in arg1.columns])
])
return layout
@callback(
Output('table', 'data'),
Input('my-numeric-input-1', 'value'),
)
def updateTable(x):
if x>0:
#ERROR here does not recognise the veriable arg1##
arg1.iloc[1,1] = arg1.iloc[1,1]*x #I.e. do stuff to the table
return arg1.to_dict('records')
return arg1.to_dict('records')
Goal: I have a simple dataframe that is being produced in page1.py and i want to pass that df into a layout function called 'update_page' that is created in layout.py (Note: i want to create multiple pages so i figured it is more code efficient to use single a layout function). Using a numeric input box i want to update the df using a callback however i get an error saying that it does not recognise the dataframe. Is there a way to update the code so that the @callback recognises the argument of the layout function and updates the df.
Thank you in advance.
The variable arg1
is defined as a parameter of the function update_page
and only exists in the scope of that function, it doesn't exist in the callback.
What you can do instead is to get the table's data
using a State
and work on that object directly (a State
allows you to pass along extra values to the callback without firing it).
Also, you probably don't want to update the callback output when the data remain unchanged, which can be achieved by raising a PreventUpdate
exception.
@callback(
Output('table', 'data'),
Input('my-numeric-input-1', 'value'),
State('table', 'data'),
)
def updateTable(x, data):
if x>0:
# do stuff to `data`
return data
raise PreventUpdate