From: Jan Szejko Date: Mon, 9 May 2016 14:06:32 +0000 (+0200) Subject: fix csv export of contact forms (blind voodoo) X-Git-Url: https://git.mdrn.pl/edumed.git/commitdiff_plain/9616d8fcb2932b9556aea942fc19000111da2a13?hp=28c55765f8f5edc8af2c43e49f5172a768d18eef fix csv export of contact forms (blind voodoo) --- diff --git a/contact/admin.py b/contact/admin.py index e9e10a0..7581666 100644 --- a/contact/admin.py +++ b/contact/admin.py @@ -7,6 +7,7 @@ from django.utils.safestring import mark_safe from django.conf.urls import patterns, url from django.http import HttpResponse, Http404 +from edumed.utils import UnicodeCSVWriter from .forms import contact_forms, admin_list_width from .models import Contact @@ -139,7 +140,7 @@ def extract_view(request, form_tag, extract_type_slug): contacts_by_spec.setdefault(tuple(keys), []).append(contact) response = HttpResponse(content_type='text/csv') - csv_writer = csv.writer(response) + csv_writer = UnicodeCSVWriter(response) # Generate list for each body key set for keys, contacts in contacts_by_spec.items(): @@ -156,7 +157,7 @@ def extract_view(request, form_tag, extract_type_slug): for key in keys: if key not in record: record[key] = '' - csv_writer.writerow([record[key].encode('utf-8') for key in keys]) + csv_writer.writerow([record[key] for key in keys]) csv_writer.writerow([]) response['Content-Disposition'] = 'attachment; filename="kontakt.csv"' diff --git a/edumed/utils.py b/edumed/utils.py new file mode 100644 index 0000000..756ffa3 --- /dev/null +++ b/edumed/utils.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +import codecs +import csv + +import cStringIO + + +# source: https://docs.python.org/2/library/csv.html#examples +class UnicodeCSVWriter(object): + """ + A CSV writer which will write rows to CSV file "f", + which is encoded in the given encoding. + """ + + def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): + # Redirect output to a queue + self.queue = cStringIO.StringIO() + self.writer = csv.writer(self.queue, dialect=dialect, **kwds) + self.stream = f + self.encoder = codecs.getincrementalencoder(encoding)() + + def writerow(self, row): + self.writer.writerow([s.encode("utf-8") for s in row]) + # Fetch UTF-8 output from the queue ... + data = self.queue.getvalue() + data = data.decode("utf-8") + # ... and reencode it into the target encoding + data = self.encoder.encode(data) + # write to the target stream + self.stream.write(data) + # empty queue + self.queue.truncate(0) + + def writerows(self, rows): + for row in rows: + self.writerow(row) \ No newline at end of file