UPDATE: I got the zip file to be created, but the response still isn't working properly. Here's the updated code.
def index(request):
if request.is_ajax():
uploaded = request.body
newstring = "{\"testdata\": [" + uploaded + "]}"
data = json.loads(newstring)
num_lines = sum(len(v) for v in data.itervalues())
testing(data, num_lines)
zip_subdir = 'testapi'
zip_filename = '%s.zip' % zip_subdir
zf = z.ZipFile(zip_filename, mode='w')
zf.write('Test.xlsx')
zf.close()
zip_file = open(zip_filename, 'r')
response = HttpResponse(zip_file, content_type='application/x-zip-compressed')
response['Content-Disposition'] = 'attachment; filename=%s' % zip_filename
return response
Just to make sure, I deleted the zip file and Excel spreadsheet, and after running the program, both were created properly. The Excel spreadsheet was populated with data, and a copy of it was put into the generated zip archive. However, it still is not getting sent to the user. Any idea what might be going wrong with the response? No errors are showing up, but the zip file isn't being delivered.
Original question below.
I'm trying to get my Django application to write files to a zip and send them to the user. This is part of the code I have in my view:
def index(request):
if request.is_ajax():
uploaded = request.body
newstring = "{\"testdata\": [" + uploaded + "]}"
data = json.loads(newstring)
num_lines = sum(len(v) for v in data.itervalues())
testing(data, num_lines)
zip_subdir = 'testapi'
zip_filename = '%s.zip' % zip_subdir
s = StringIO.StringIO()
zf = z.ZipFile(s, 'w')
zf.write('Test.xlsx')
zf.close()
response = HttpResponse(s.getvalue(), content_type='application/x-zip-compressed')
response['Content-Disposition'] = 'attachment; filename=%s' % zip_filename
return response
Essentially, the user presses a button, an ajax request is made to get JSON from an external API, and then this JSON data is sent to the server and put into an Excel spreadsheet (called 'Test.xlsx'). All of that works properly.
The issue is that the zip archive ('testapi.zip') is not being created properly. What's odd is that it's the same code I used previously when the user uploaded a JSON dump via a form (rather than use an API), and it worked before. However, now it won't create a zip file. Additionally, even if I manually place a zip file called 'testapi.zip' in the proper directory, the response doesn't work (again, this used to work before - in the prior version of this app, the zip file was sent to the user and automatically downloaded). No errors are returned, but nothing happens.
Any idea what might be going on?