无法将 Presentation 对象从 python-pptx 库转换为上传到 MS Graph API 服务端点

Unable to transform Presentation object from python-pptx library to upload to MS Graph API service endpoint

上下文

我有一个 python 脚本,它使用 openpyxl 和 python-pptx 库分别生成工作簿和 PowerPoint。这些文件需要通过 Microsoft Graph API 作为八位字节流直接从虚拟内存上传。

障碍物

多亏了 save_virtual_workbook 方法,工作簿的所有功能都很好,returns 一个内存中的工作簿;但据我所知,没有像 save_virtual_presentation 这样的类似方法,因此以可以通过 io.BytesIO.read() 方法流式传输的形式获取 Presentation 对象一直是一个挑战。

python.pptx documentationPresentation.save(file) 有效...

"where file can be either a path to a file (a string) or a file-like object."

除了执行 POC 时,我没有保存到本地文件系统的选项,所以我尝试了各种方法来处理类文件对象。 None 接近被 MS Graph API 端点的放置请求接受,除了下面的尝试。

最近的小姐

在这种情况下,prs 是在前面的代码中创建的 Presentation 对象,由于它有 556 行,我没有在此处包含它。

<<Omitted code that generates the Workbook and PowerPoint, of which prs is an output>>

headers = {'Authorization' : 'Bearer {0}'.format(access_token),
           'Accept' : 'application/json',
           'Content-Type' : 'application/octet-stream'}

endpoint_url = 'https://graph.microsoft.com/v1.0/me/drive/items/<<removed id>>:/Test.pptx:/content'

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

response = requests.put(url=endpoint_url,
                        headers=headers,
                        data=io.BytesIO.read(target_stream),
                        verify=False,
                        params=None) 

put 请求成功,但保存到服务端点的文件是空 pptx shell。我已经排除 prs 本身是一个空的 pptx shell,所以我得出结论 target_stream 不是 prs.

的有效转换

总结

有人可以帮助我建议如何将 Presentation 对象 prs 转换为我可以插入 data=io.BytesIO.read(<<input>>) 并成功上传到 MS Graph API 端点的对象吗?非常感谢!

一切看起来都很好,直到您读取 BytesIO 对象。在 put() 调用中,尝试使用 data=target_stream.getvalue() 而不是现在的 read() 调用。这是以字节形式获取 BytesIOStringIO 对象内容的常规方法。