Как обработать загруженный почтовый файл в Da sh плотно? - PullRequest
0 голосов
/ 17 марта 2020

Используя dcc.Upload, вы можете создать функцию перетаскивания или загрузки на основе кнопок в инструментальной панели Da sh Plotly. Однако в документации есть ограничение на обработку определенного c типа файла, такого как .zip. Вот фрагмент загрузки html:

dcc.Upload(
    id='upload_prediction',
    children=html.Div([
        'Drag and Drop or ',
        html.A('Select Files'),
        ' New Predictions (*.zip)'
    ]),
    style={
        'width': '100%',
        'height': '60px',
        'lineHeight': '60px',
        'borderWidth': '1px',
        'borderStyle': 'dashed',
        'borderRadius': '5px',
        'textAlign': 'center',
        'margin': '10px'
    },
    accept=".zip",
    multiple=True
)

Затем, когда я пытаюсь проверить загруженный файл с помощью этого фрагмента:

@app.callback(Output('output_uploaded', 'children'),
              [Input('upload_prediction', 'contents')],
              [State('upload_prediction', 'filename'),
               State('upload_prediction', 'last_modified')])
def test_callback(list_of_contents, list_of_names, list_of_dates):
    for content in list_of_contents:
        print(content)

Тип содержимого после загрузки - 'data : применение / х-молния сжатый; base64' . Как обработать этот тип файла в Da sh Plotly (например, где-нибудь извлечь его)?

Аналогичный вопрос был задан на форуме plotly без ответов: https://community.plot.ly/t/dcc-upload-zip-file/33976

1 Ответ

0 голосов
/ 17 марта 2020

Da sh Plotly предоставляет загруженный файл в формате строки base64. Что вам нужно сделать, это сначала декодировать его, а затем обработать его как строку байтов, которая позже может быть использована для инициализации ZipFile класса (это встроенный инструмент в python).

import io
import base64
from zipfile import ZipFile


@app.callback(Output('output_uploaded', 'children'),
              [Input('upload_prediction', 'contents')],
              [State('upload_prediction', 'filename'),
               State('upload_prediction', 'last_modified')])
def update_output(list_of_contents, list_of_names, list_of_dates):
    for content, name, date in zip(list_of_contents, list_of_names, list_of_dates):
        # the content needs to be split. It contains the type and the real content
        content_type, content_string = content.split(',')
        # Decode the base64 string
        content_decoded = base64.b64decode(content_string)
        # Use BytesIO to handle the decoded content
        zip_str = io.BytesIO(content_decoded)
        # Now you can use ZipFile to take the BytesIO output
        zip_obj = ZipFile(zip_str, 'r')

        # you can do what you wanna do with the zip object here
...