Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added stream to CSV #337

Merged
merged 2 commits into from
Jun 28, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,4 @@ junit-py27.xml

# pyenv noise
.python-version
tablib.egg-info/*
11 changes: 9 additions & 2 deletions tablib/formats/_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
DEFAULT_DELIMITER = unicode(',')


def export_set(dataset, **kwargs):
"""Returns CSV representation of Dataset."""
def export_stream_set(dataset, **kwargs):
"""Returns CSV representation of Dataset as file-like."""
stream = StringIO()

kwargs.setdefault('delimiter', DEFAULT_DELIMITER)
Expand All @@ -24,6 +24,13 @@ def export_set(dataset, **kwargs):
for row in dataset._package(dicts=False):
_csv.writerow(row)

stream.seek(0)
return stream


def export_set(dataset, **kwargs):
"""Returns CSV representation of Dataset."""
stream = export_stream_set(dataset, **kwargs)
return stream.getvalue()


Expand Down
20 changes: 19 additions & 1 deletion test_tablib.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import tablib
from tablib.compat import markup, unicode, is_py3
from tablib.core import Row
from tablib.formats import csv as csv_format
from tablib.formats import _csv as csv_module


class TablibTestCase(unittest.TestCase):
Expand Down Expand Up @@ -262,6 +262,24 @@ def test_csv_export(self):

self.assertEqual(csv, self.founders.csv)

def test_csv_stream_export(self):
"""Verify exporting dataset object as CSV from file object."""

# Build up the csv string with headers first, followed by each row
csv = ''
for col in self.headers:
csv += col + ','

csv = csv.strip(',') + '\r\n'

for founder in self.founders:
for col in founder:
csv += str(col) + ','
csv = csv.strip(',') + '\r\n'

csv_stream = csv_module.export_stream_set(self.founders)
self.assertEqual(csv, csv_stream.getvalue())

def test_tsv_export(self):
"""Verify exporting dataset object as TSV."""

Expand Down