pythonflaskpython-pptx

downloading PPTX created by python-pptx in a flask app


I am using Python-pptx in a web app, that programmatically creates a powerpoint and then allows the user to download at the end. People can upload images, etc, and it inserts it into the powerpoint for them.

Works great, however currently I am saving the PowerPoint to the "static" folder and then creating a download link with its file path.

Ideally, I want the file to never be saved to the server. This is to prevent privacy issues regarding sensitive information. It would also be great if people didn’t have to log in. Just a simple, secure way to make powerpoints.

I tried to get send_file to work to no avail. I think it is the solution though.

Here’s what I tried:

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

Would appreciate any help! It's my first flask app!

Thank you in advance!


Solution

  • UPDATE: In Python 3 you would use:

    import io
    
    outfile = io.BytesIO()
    prs.save(outfile)
    

    You can save the presentation to an "in-memory" file, something roughly like this:

    from StringIO import StringIO
    
    out_file = StringIO()
    prs.save(out_file)
    

    python-pptx likes memory streams like StringIO just fine and will happily write the file to it just like it was a disk file. Then you can send the file for download just like it was an open disk file handle.

    There's a little bit more in the documentation here: http://python-pptx.readthedocs.io/en/latest/user/presentations.html#opening-a-file-like-presentation