我目前正在使用下面的脚本从我创建的破折号下载数据表。下载工作正常,但是当我在本地托管 Dash 并尝试通过另一个系统单击下载按钮时,文件正在主机上下载,而不是在用户计算机上下载。如果我的问题看起来很愚蠢,我深表歉意,因为我对 Dash 和 python 很陌生。
html.Button(id="save-button", n_clicks=0, children="Save"),
html.Div(id="output-1", children="Press button to save data at your desktop")
@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 dash.PreventUpdate
else:
df = pd.DataFrame(table1).to_csv(
'C:\\Users\\'+loggedin_user + '\\Desktop\\Open_Queue_Dump.csv', index=False)
return "Data Submitted"
查看破折号扩展包 https://pypi.org/project/dash-extensions/,帮助我使用我的应用程序。它有一个名为“下载”的组件。当您将某些内容返回给它时,系统会提示用户下载它。所以你的代码可能看起来像这样:
import io
import dash
import dash_html_components as html
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
from dash_extensions import Download
import dash_table
from flask import Flask
import pandas as pd
server = Flask(__name__)
app = dash.Dash(server=server)
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/solar.csv')
app.layout = html.Div(
[
Download(id="download"),
html.Button("Save",
id="save-button"),
html.Div("Press button to save data at your desktop",
id="output-1"),
dash_table.DataTable(
id='table',
columns=[{"name": i, "id": i} for i in df.columns],
data=df.to_dict('records'),
)
]
)
@app.callback(
Output("download", "data"),
Input("save-button", "n_clicks"),
State("table", "data"))
def download_as_csv(n_clicks, table_data):
df = pd.DataFrame.from_dict(table_data)
if not n_clicks:
raise PreventUpdate
download_buffer = io.StringIO()
df.to_csv(download_buffer, index=False)
download_buffer.seek(0)
return dict(content=download_buffer.getvalue(), filename="some_filename.csv")
if __name__ == '__main__':
app.run_server()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)