我在一个网络应用程序中使用Python-pptx,它以编程方式创建一个powerpoint,然后允许用户在最后下载。人们可以上传图像等,它会将其插入到他们的幻灯片中。
效果很好,但目前我将 PowerPoint 保存到“静态”文件夹,然后使用其文件路径创建下载链接。
理想情况下,我希望文件永远不会保存到服务器上。这是为了防止有关敏感信息的隐私问题。如果人们不必登录,那就太好了。这只是一种简单、安全的制作幻灯片的方式。
我尝试让 send_file 工作但无济于事。我认为这是解决方案。
这是我尝试过的:
prs = Presentation()
file_name = 'static/' + file_name + '.pptx'
root_dir = os.path.dirname(os.getcwd())
path = os.path.join(root_dir, 'project', 'static', 'test.pptx')
return send_file(prs, as_attachment=True)
# also tried:
# return send_file(path, mimetype='applicationvnd.openxmlformats-officedocument.presentationml.presentation', as_attachment=True)
# which loads the page, but doesn’t trigger a download,just loads a blank page.
# plus, it is referencing a file path which means the file was saved on the server
将不胜感激任何帮助!这是我的第一个烧瓶应用程序!
提前谢谢您!
更新: 在 Python 3 中你可以使用:
import io
outfile = io.BytesIO()
prs.save(outfile)
您可以将演示文稿保存到“内存中”文件,大致如下:
from StringIO import StringIO
out_file = StringIO()
prs.save(out_file)
python-pptx
喜欢像 StringIO 这样的内存流,并且会很乐意将文件写入其中,就像写入磁盘文件一样。然后您可以发送文件以供下载,就像它是打开的磁盘文件句柄一样。
这里的文档还有更多内容:http://python-pptx.readthedocs.io/en/latest/user/presentations.html#opening-a-file-like-presentation