Skip to content

Commit

Permalink
Add TextIOWrapper instead of StringIO buffer
Browse files Browse the repository at this point in the history
  • Loading branch information
micsucmed committed Nov 9, 2023
1 parent e077e92 commit 038a842
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 12 deletions.
21 changes: 15 additions & 6 deletions newdle/export.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import csv
import datetime
from io import BytesIO, StringIO
from contextlib import contextmanager
from io import BytesIO, TextIOWrapper

from xlsxwriter import Workbook

Expand All @@ -26,15 +27,23 @@ 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)
buffer = BytesIO()
output = StringIO()
writer = csv.writer(output, dialect='unix')
writer.writerows(rows)
buffer.write(output.getvalue().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)
output.close()

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
8 changes: 4 additions & 4 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"
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,,,Hello world
Tony Stark,,available,,,"Hello, world"
Binary file modified tests/export/answers.xlsx
Binary file not shown.

0 comments on commit 038a842

Please sign in to comment.