使用 io.StringIO() 和 io.BytesIO() 时出错

Error using io.StringIO() and io.BytesIO()

我正在尝试从 AWS s3 存储桶中读取一个 .pptx 文件,更改幻灯片中图表的基础数据,然后让用户能够下载该文件。出于某种原因,我一直收到预期的错误字符串参数,在尝试将演示文稿保存到 io.StringIO 对象时收到 'bytes'。你能指导我在这方面做错了什么吗?我的代码如下:

import pandas as pd
import boto3
import io
from pptx import Presentation
from pptx.chart.data import CategoryChartData, ChartData
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import dash_bootstrap_components as dbc
from dash_extensions import Download
from dash_extensions.snippets import send_file


## Display Settings
pd.set_option("max_columns", 20)
pd.set_option("max_colwidth", 50)
pd.set_option("display.width", 2000)
pd.set_option("max_rows", 100)




S3_BUCKET_UNIVERSE = 'template-presentation'
S3_UNIVERSES_FILENAME = 'report_v1.pptx'
#
# need to pass mfa credentials locally
session = boto3.Session(profile_name='mfa')
s3 = session.client('s3')

#get the object and put into a dataframe
obj = s3.get_object(Bucket=S3_BUCKET_UNIVERSE, Key=S3_UNIVERSES_FILENAME)
presentation_path = obj['Body'].read()

prs = Presentation(io.BytesIO(presentation_path))

print(type(prs))
output = io.StringIO()
print(type(output))

prs.save(output)


app = dash.Dash(prevent_initial_callbacks=True)
app.layout = html.Div([html.Button("Download", id="btn"), Download(id="download")])

@app.callback(Output("download", "data"), [Input("btn", "n_clicks")])
def func(n_clicks):
    return send_file(output)

if __name__ == '__main__':
    app.run_server()

StringIO 在 Python 2 中工作(现在仍然如此),但在 Python 3 中没有工作。

改用io.BytesIO

output = io.BytesIO()
prs.save(output)

A str in Python 2 是字节,unicode 是字符。在Python3中,str是字符(unicode),bytes是字节。