问题描述
数据 solar.csv
: https://raw.githubusercontent.com/plotly/datasets/master/solar.csv
这是一个代码:
import dash
import dash_table
import dash_html_components as html
from dash.dependencies import Input, Output, State
import pandas as pd
from dash.exceptions import PreventUpdate
df = pd.read_csv('D:/solar.csv')
app = dash.Dash(__name__)
app.layout = html.Div([
dash_table.DataTable(
id='table',
columns=[{"name": i, "id": i} for i in df.columns],
data=df.to_dict("rows"),
editable=True
),
html.Button(id="save-button",n_clicks=0,children="Save"),
html.Div(id="output-1",children="Press button to save changes")
])
@app.callback(
Output("output-1","children"),
[Input("save-button","n_clicks")],
[State("table","data")]
)
def selected_data_to_csv(nclicks,table1):
if nclicks == 0:
raise PreventUpdate
else:
pd.DataFrame(table1).to_csv('D:/solar.csv',index=False)
return "Data Submitted"
if __name__ == '__main__':
app.run_server(debug=True)
当我在浏览器中编辑表中的数据时,按保存按钮后,修改后的数据将正确保存在 solar.csv
中.问题是,如果我刷新页面,则会显示旧数据(未修改).
When I am editing data in table from browser and after pressing the save button the modified data is saved correctly in solar.csv
. The problem is that, if I refresh page old data (non-modified) data is displayed.
我尝试了几种方法,例如在 selected_data_to_csv()
中使用全局变量,但没有任何运气.
I tried several ways like using global variables inside selected_data_to_csv()
but without any luck.
问题:如何在重新加载网页时修改上面的代码以显示修改后的数据?
Question: How to modify code above in order to show modified data when I reload webpage?
以下来源的原始代码:
推荐答案
啊,好问题.
为此,请将app.layout设置为等于函数.然后,它应该在您刷新时评估该功能,并以此来获取更新的,已保存的向下数据.
In order to do so, set the app.layout equal to a function. Then it should evaluate that function when you refresh, and in doing so pull in the updated, saved down data.
即下面的layout_function:
i.e. the layout_function below:
import dash
import dash_table
import dash_html_components as html
from dash.dependencies import Input, Output, State
import pandas as pd
from dash.exceptions import PreventUpdate
#df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/solar.csv')
df = pd.read_csv('H://R//filename.csv')
app = dash.Dash(__name__)
def layout_function():
df = pd.read_csv('H://R//filename.csv')
return html.Div([
dash_table.DataTable(
id='table',
columns=[{"name": i, "id": i} for i in df.columns],
data=df.to_dict("rows"),
editable=True
),
html.Button(id="save-button",children="Save",n_clicks=0),
html.Div(id="output-1",children="Press button to save changes")
])
app.layout = layout_function
@app.callback(
Output("output-1","children"),
[Input("save-button","n_clicks")],
[State("table","data")]
)
def selected_data_to_csv(nclicks,table1):
if nclicks == 0:
raise PreventUpdate
else:
pd.DataFrame(table1).to_csv('H://R//filename.csv',index=False)
return "Data Submitted"
if __name__ == '__main__':
app.run_server(debug=True)
这篇关于重新加载页面时不显示数据表组件中的已修改数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!