Skip to content

Commit

Permalink
Use CSV writer for answer exports (#456)
Browse files Browse the repository at this point in the history
  • Loading branch information
micsucmed authored Dec 8, 2023
1 parent f58f9ef commit 1c00f21
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 7 deletions.
20 changes: 17 additions & 3 deletions newdle/export.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import csv
import datetime
from io import BytesIO
from contextlib import contextmanager
from io import BytesIO, TextIOWrapper

from xlsxwriter import Workbook

Expand All @@ -25,12 +27,24 @@ def _generate_answers_for_export(newdle):
return rows


@contextmanager
def csv_text_io_wrapper(buf):
"""IO wrapper to use the csv reader/writer on a byte stream."""
w = TextIOWrapper(buf, encoding='utf-8-sig', newline='')
try:
yield w
finally:
w.detach()


def export_answers_to_csv(newdle):
rows = _generate_answers_for_export(newdle)
csv = '\n'.join([','.join(row) for row in rows])
buffer = BytesIO()
buffer.write(csv.encode('utf-8-sig'))
with csv_text_io_wrapper(buffer) as csvbuf:
writer = csv.writer(csvbuf, dialect='unix', quoting=csv.QUOTE_MINIMAL)
writer.writerows(rows)
buffer.seek(0)

return buffer


Expand Down
4 changes: 2 additions & 2 deletions tests/api_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1374,13 +1374,13 @@ def test_answer_export(snapshot, monkeypatch, flask_client, dummy_uid):
snapshot.snapshot_dir = Path(__file__).parent / 'export'
p1 = Participant.query.filter_by(code='part1').first()
p1.answers = {datetime(2019, 9, 11, 14, 0): Availability.available}
p1.comment = 'Available comment'
p1.comment = 'Hello, world'
Participant.query.filter_by(code='part2').first().answers = {
datetime(2019, 9, 11, 14, 0): Availability.unavailable
}
p3 = Participant.query.filter_by(code='part3').first()
p3.answers = {datetime(2019, 9, 11, 14, 0): Availability.ifneedbe}
p3.comment = 'Comment'
p3.comment = 'Hello world'

resp = flask_client.get(
url_for('api.export_participants', code='dummy', format='csv'),
Expand Down
4 changes: 2 additions & 2 deletions tests/export/answers.csv
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Participant name,2019-09-11T13:00,2019-09-11T14:00,2019-09-12T13:00,2019-09-12T13:30,Comment
Albert Einstein,,unavailable,,,
Guinea Pig,,ifneedbe,,,Comment
Tony Stark,,available,,,Available comment
Guinea Pig,,ifneedbe,,,Hello world
Tony Stark,,available,,,"Hello, world"
Binary file modified tests/export/answers.xlsx
Binary file not shown.

0 comments on commit 1c00f21

Please sign in to comment.