我需要将CSV转换为ZIP,然后将其作为HttpResponse发送到ajax

时间:2019-01-08 13:30:42

标签: ajax python-3.x django-views httpresponse export-to-csv

我正在努力将csv转换为zip。我必须从MySQL存储过程结果创建CSV,然后将其压缩为zip。制成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

}

0 个答案:

没有答案