Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Support file objects in Builder.add_file.
Update the Builder.add_file() to accept file objects so that we do not
have to load all the data into the RAM at once.
  • Loading branch information
jone committed Feb 1, 2017
1 parent 95f90e1 commit f2a799e
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
2 changes: 2 additions & 0 deletions docs/HISTORY.txt
Expand Up @@ -4,6 +4,8 @@ Changelog
1.5.1 (unreleased)
------------------

- Support file objects in Builder.add_file. [jone]

- Drop Plone 4.1 support.


Expand Down
8 changes: 5 additions & 3 deletions ftw/pdfgenerator/builder.py
Expand Up @@ -28,9 +28,11 @@ def add_file(self, filename, data):
raise BuildTerminated('The build is already terminated.')

path = os.path.join(self.build_directory, filename)
file_ = open(path, 'wb')
file_.write(data)
file_.close()
with open(path, 'wb') as fio:
if hasattr(data, 'read'):
shutil.copyfileobj(data, fio)
else:
fio.write(data)

def build(self, latex):
if self._terminated:
Expand Down
11 changes: 11 additions & 0 deletions ftw/pdfgenerator/tests/test_builder.py
Expand Up @@ -8,6 +8,7 @@
from ftw.pdfgenerator.testing import PREDEFINED_BUILD_DIRECTORY_LAYER
from ftw.testing import MockTestCase
from mocker import MATCH, ANY
from StringIO import StringIO
from zipfile import ZipFile
from zope.component import getUtility
from zope.interface.verify import verifyClass
Expand Down Expand Up @@ -52,6 +53,16 @@ def test_add_file(self):
'File not found: {0}'.format(filepath))
self.assertEqual(open(filepath).read(), 'Foo\nBar')

def test_add_file_by_file_object(self):
builder = getUtility(IBuilderFactory)()
builder.add_file('foo.txt', StringIO('Foo\nBar'))

self.assertTrue(os.path.exists(self.builddir))
filepath = os.path.join(self.builddir, 'foo.txt')
self.assertTrue(os.path.exists(filepath),
'File not found: {0}'.format(filepath))
self.assertEqual(open(filepath).read(), 'Foo\nBar')

def test_terminated_exception_raised(self):
builder = self.mocker.patch(getUtility(IBuilderFactory)())
fake_pdf_path = os.path.join(self.builddir, 'export.pdf')
Expand Down

0 comments on commit f2a799e

Please sign in to comment.