pythonhtmlcgizipserver-side-scripting

Return Dynamically Zipped File Based On HTML Form Data (Confirm Download Dialog?)


I have an HTML form whose action is set to my Python script in which I test which checkboxes were selected in the form. From this information, I use my script to create a zip file containing the files corresponding to the checked checkboxes. I need to give this dynamically zipped file back to the user as simply as possible. I figured that a confirm download dialog would be best, but if there's some other widely accepted standard, I'm all ears. The host server is Apache with Python supported, and here's my script code:

#!usr/bin/env python

from zipfile import *;
import cgi, cgitb, os, os.path, re, sys; cgitb.enable();

def main():
    form = cgi.FieldStorage();
    zipfile = ZipFile( "zipfiles.zip" );

    if( form.getvalue( "checkbox1" ) ):
        zip.write( "../files/file1.txt", "zipfile1.txt" );

    if( form.getvalue( "checkbox2" ) ):
        zip.write( "../files/file2.txt", "zipfile2.txt" );

    zip.close();

    print ('Content-Type:application/octet-stream; name="zipfiles.zip');
    print ('Content-Disposition:attachment; filename="zipfiles.zip');

if( __name__ == "__main__" ):
    main();

This code does not work and spits out an Internal Server Error, so please explain to me what's going wrong and how I can get zipfiles.zip to the user. This is only my third day of using Python; therefore, I know very little about what's going on, so please don't skip over anything you think I might know because I probably don't.


Solution

  • Thank you, falsetru and SDilmac. Below is the code that I was missing which you pointed me to. It still didn't get rid of my error, but that had something to do with our host server's suexec_log permissions.

    Here's the full write-up of what I'm pretty sure the working code would be if not for the permissions error:

    #!usr/bin/env python
    
    from zipfile import *;
    import cgi, cgitb; cgitb.enable();
    
    def main():
        form = cgi.FieldStorage();
    
        with ZipFile( "zipfiles.zip" ) as zipFile:
            if( form.getvalue( "checkbox1" ) ):
                zip.write( "../files/file1.txt", "zipfile1.txt" );
    
            if( form.getvalue( "checkbox2" ) ):
                zip.write( "../files/file2.txt", "zipfile2.txt" );
    
        print ( 'Content-Type:application/octet-stream; name="zipfiles.zip"\n\n' );
        print ( 'Content-Disposition:attachment; filename="zipfiles.zip"\n\n\n' );
        with open( zipFile, "rb" ) as zip:
            print( zip.read() );
    
    if( __name__ == "__main__" ):
        main();