Bill Chappell
Bill Chappell

Reputation: 311

Server-side python returning a zip file for a download

Using my client I pass a parameter by get to a python script on the server, it runs a process and creates a zip file. In my client side JavaScript my ajax call just tells me it was able to pass the data to my python script.

I've tried sys.stdout.write(b"zipfilename") but nothing happens. If I can't pass the file back, is there a way to pass something back so my JavaScript knows it's done? I'm not using NODE or Angular. My python script does run and creates the zip file on the server but the JavaScript page doesn't know it nor does a download dialog appear. I'm missing something basic but I can't find it.

My JS AJAX call:

  $.ajax({
       url: theUrl,
       type: 'get',
       success: function(response){

       }      });

The end of my python script:

def createZip(v, charset=None):

    with ZipFile(v +'.zip', 'w') as myzip:
        myzip.write(v +'.shp')
        myzip.write(v +'.shx')
        myzip.write(v +'.dbf')
        myzip.write(v +'.prj')

    return 'c:/dev/python/'+ v + '.zip'

createZip(fn)

Upvotes: 2

Views: 699

Answers (1)

Daniel Finch
Daniel Finch

Reputation: 443

It's hard to tell based on the limited code provided, but here's some general points:

  • sys.stdout.write is going to write to the output of the application running the Python script, not to a HTTP response (unless it's running as a WSGI application).
  • If you are writing the HTTP response in a WSGI type of application, then you're going to need to include the entire HTTP response body, including the multipart and content type headers so that the browser knows what is coming back (otherwise it's just a feed of meaningless bytes).
  • A download prompt will only appear if the browser loads a page which returns a application/octet-stream content type (or the download attribute is set on the anchor which links to the file).
  • An AJAX call wouldn't cause a download to occur in the foreground browser, it would appear in your developer tools 'Network' tab and the AJAX response variable would contain the data, but this isn't automatically pushed to the browser as a downloadable file.

Upvotes: 2

Related Questions