【问题标题】:Using the Dash Upload component to post csv file使用 Dash Upload 组件发布 csv 文件
【发布时间】:2020-04-13 13:18:58
【问题描述】:

我想使用 Dash 上传组件(请参阅 Example from Dash Documentation)上传 csv 文件并将其发布到文件服务器。我希望它像working Postman csv Post-Request 一样简单。 我的回调当前如下所示:

@app.callback(
Output(component_id="eventlog-dropdown", component_property="options"),
[Input(component_id="upload-data", component_property="contents"),
 Input(component_id="upload-data", component_property="filename")]
)
def upload_eventlog(uploaded_contents, uploaded_filename):
    if uploaded_contents is not None:
        eventlog_data = [
            parse_contents(c, n) for c, n in
            zip(uploaded_contents, uploaded_filename)]

        files = {'file': (uploaded_filename[0], str(eventlog_data))}

        print(files)

        requests.post(MIDDLEWARE_ENDPOINT+"data/upload-eventlog", files=files)

        #Updates the dropdown "eventlog-dropdown"
        files = requests.get(MIDDLEWARE_ENDPOINT + 'data/geteventloglist').json()
        options = [{'label': i, 'value': i} for i in files]
        return options
    elif uploaded_contents is None:
        files = requests.get(MIDDLEWARE_ENDPOINT + 'data/geteventloglist').json()
        options = [{'label': i, 'value': i} for i in files]
        return options

解析内容函数如下所示:

def parse_contents(contents, filename):
content_type, content_string = contents.split(',')

decoded = base64.b64decode(content_string)
try:
    if 'csv' in filename:
        # Assume that the user uploaded a CSV file
        df = pd.read_csv(
            io.StringIO(decoded.decode('utf-8')))
        return df
    elif 'xls' in filename:
        # Assume that the user uploaded an excel file
        df = pd.read_excel(io.BytesIO(decoded))
        return df
except Exception as e:
    print(e)
    return html.Div([
        'There was an error processing this file.'
    ])

帖子“有效”。它发布 csv 文件,并且 csv 文件存储在文件服务器上。但是,csv 不再以逗号分隔并被截断:

69  FN322        Landing  2019-05-22 04:35         Berlin       12:20      4           12.333333
70  FN322  Baggage claim  2019-05-22 03:05         Berlin       01:40      5            1.666667

[71 rows x 7 columns]]

你们知道像 Postman 那样在 Dash Upload 组件中发布上传的文件名和内容的简单方法吗?或者我怎样才能至少保存所有文件内容?

非常感谢您,祝您有美好的一天!

【问题讨论】:

    标签: csv post python-requests postman plotly-dash


    【解决方案1】:

    我想通了。这是因为以下代码行:

    `df = pd.read_csv(
        io.StringIO(decoded.decode('utf-8')))`
    

    要上传 csv 文件,我们不希望它是文本流。它需要是一个类似字节的对象。代码:

    decoded = base64.b64decode(content_string)
    

    已经返回了一个字节对象,所以我们只需要返回那个对象。所以,parse_contents() 函数现在看起来像这样:

    def parse_contents(contents, filename):
        content_type, content_string = contents.split(',')
    
        decoded = base64.b64decode(content_string)
    
        try:
            if 'csv' in filename:
                # Assume that the user uploaded a CSV file
                return decoded
         except Exception as e:
            return html.Div([
            'There was an error processing this file.'
        ])
    

    请注意,我目前只对 csv 文件感兴趣。这就是我删除 xlsx 部分的原因。不幸的是,我不知道该代码是否也适用于 xlsx 文件。 代码

    eventlog_data = [
            parse_contents(c, n) for c, n in
            zip(uploaded_contents, uploaded_filename)]
    

    定义一个列表,解码后的字节对象是该列表中的第一个元素。因此,我们的 post-request 的 files-argument 必须取出 eventlog-data 的第一个元素才能发送字节数据:

    files = {'file': (uploaded_filename[0], eventlog_data[0])}
    

    最终的回调如下所示:

    @app.callback(
    Output(component_id="eventlog-dropdown", component_property="options"),
    [Input(component_id="upload-data", component_property="contents"),
     Input(component_id="upload-data", component_property="filename")]
    )
    def upload_eventlog(uploaded_contents, uploaded_filename):
        if uploaded_contents is not None:
            eventlog_data = [
                parse_contents(c, n) for c, n in
                zip(uploaded_contents, uploaded_filename)]
            files = {'file': (uploaded_filename[0], eventlog_data[0])}
            requests.post(MIDDLEWARE_ENDPOINT+"predictivemonitor/upload-eventlog", files=files)
    
            #Updates the dropdown "eventlog-dropdown"
            files = requests.get(MIDDLEWARE_ENDPOINT + 'predictivemonitor/geteventloglist').json()
            options = [{'label': i, 'value': i} for i in files]
            return options
        elif uploaded_contents is None:
            #Still updates the dropdown "eventlog-dropdown" even if the content is empty
            files = requests.get(MIDDLEWARE_ENDPOINT + 'predictivemonitor/geteventloglist').json()
            options = [{'label': i, 'value': i} for i in files]
            return options
    

    【讨论】:

      猜你喜欢
      • 2020-05-30
      • 2022-01-22
      • 2018-12-02
      • 2020-12-14
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      • 1970-01-01
      • 2020-09-10
      相关资源
      最近更新 更多