[我正在尝试使用Dash编写一个简单的Web应用程序,其中用户上传了一个csv文件,使用熊猫在数据框中进行了一些处理,然后用户可以通过链接下载新的csv文件。 。虽然我擅长数据分析,但对Dash还是很陌生。这可能是超级基础,但我不知道熊猫处理部分应该放在哪里,以及最后如何生成下载链接。
这里是代码的简化版本:
import base64
import datetime
import io
import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div(children = [
html.H2('Please upload your csv file:'),
dcc.Upload(
id= 'upload-data',
children = html.Div([
html.A('Select File')]),
style = {
'width': '100%',
'height': '60px',
'lineHeight': '60px',
'borderWidth': '1px',
'borderStyle': 'dashed',
'borderRadius': '4px',
'textAlign': 'center',
'margin': '5px'
},
),
html.Div(id='download-link')
])
def parse_contents(contents, filename):
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string)
try:
if 'csv' in filename:
# Assume the uploaded file is csv
df = pd.read_csv(io.StringIO(decoded.decode('utf-8')))
except Exception as e:
print(e)
return html.Div([
'There was an error. Please uplaod the file in csv format.'
])
return df
@app.callback(Output('download-link', 'href'),
[Input('upload-data', 'contents')])
# Data processing using pandas:
def example_func(df):
df['col2'] = df['col1']+'some string'
return df
df_new = df.apply(example_func, axis=1)
df_new.to_csv('processed_data.csv')
# Return a link to let the user download the csv file with the processed data
def download_csv (contents):
#######
if __name__ == '__main__':
app.run_server(debug=True)
任何输入将不胜感激!
首先,您需要导入这些额外的库:
import os
from urllib.parse import quote as urlquote
定义文件的位置:
UPLOAD_DIRECTORY = "/project/app_uploaded_files"
if not os.path.exists(UPLOAD_DIRECTORY):
os.makedirs(UPLOAD_DIRECTORY)
添加这些功能:
def save_file(name, content):
"""Decode and store a file uploaded with Plotly Dash."""
data = content.encode("utf8").split(b";base64,")[1]
with open(os.path.join(UPLOAD_DIRECTORY, name), "wb") as fp:
fp.write(base64.decodebytes(data))
def uploaded_files():
"""List the files in the upload directory."""
files = []
for filename in os.listdir(UPLOAD_DIRECTORY):
path = os.path.join(UPLOAD_DIRECTORY, filename)
if os.path.isfile(path):
files.append(filename)
return files
def file_download_link(filename):
"""Create a Plotly Dash 'A' element that downloads a file from the app."""
location = "/download/{}".format(urlquote(filename))
return html.A(filename, href=location)
您可以在这里找到完整的代码:Example: Upload and Download Files with Plotly Dash
希望有帮助!