Я изо всех сил в преобразовании CSV в ZIP. Я должен создать CSV из результата хранимой процедуры MySQL и затем сжать его в zip. После того, как zip был создан, я должен отправить его как Httpresponse в ajax. Но я застрял в создании CSV.
Код выглядит следующим образом:
{
def reports_ajax(request):
if request.method == 'POST':
value = request.POST.get('value')
if value == '1':
log.info('enter reports_ajax')
date_start = request.POST.get('start')
date_end = request.POST.get('end')
sql_query = "Call Payworld_Analytics.Retailer_Sales(\"{0}\",\"{1}\");".format(date_start, date_end)
cur = connection.cursor()
cur.execute(sql_query)
result = cur.fetchall()
field_names = [i[0] for i in cur.description]
csv_file = "Retailer_daily_sales_{}.csv".format(date_start)
log.info('csv file created')
#response = HttpResponse(content_type='text/csv')
#response['Content-Disposition'] = 'attachment; filename=' + csv_file
writer = csv.writer(csv_file)
writer.writerow(field_names)
for row in result:
writer.writerow(row)
zip_file = "Retailer_daily_sales{}.zip".format(date_start)
output = StringIO.StringIO()
# response = HttpResponse(mimetype='application/zip')
# response['Content-Disposition'] = 'attachment; filename=' + csv_file + '.zip'
z = zipfile.ZipFile(output, 'w')
z.writestr(csv_file, output.getvalue())
response = HttpResponse(output.getvalue(), mimetypet='application/zip')
response['Content-Disposition'] = 'attachment; filename=' + zip_file
log.info(response)
return response
}