Skip to content

Commit

Permalink
#18899 FileSystemStorage.save should support any file-like objects
Browse files Browse the repository at this point in the history
  • Loading branch information
biern committed Feb 23, 2013
1 parent 7ec2a21 commit 664855b
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
8 changes: 6 additions & 2 deletions django/core/files/storage.py
Expand Up @@ -37,13 +37,17 @@ def open(self, name, mode='rb'):


def save(self, name, content): def save(self, name, content):
""" """
Saves new content to the file specified by name. The content should be a Saves new content to the file specified by name. The content should be
proper File object, ready to be read from the beginning. a proper File object or any python file-like object, ready to be read
from the beginning.
""" """
# Get the proper name for the file, as it will actually be saved. # Get the proper name for the file, as it will actually be saved.
if name is None: if name is None:
name = content.name name = content.name


if not hasattr(content, 'chunks'):
content = File(content)

name = self.get_available_name(name) name = self.get_available_name(name)
name = self._save(name, content) name = self._save(name, content)


Expand Down
30 changes: 30 additions & 0 deletions tests/modeltests/files/tests.py
Expand Up @@ -2,6 +2,7 @@


import gzip import gzip
import shutil import shutil
import StringIO
import tempfile import tempfile


from django.core.cache import cache from django.core.cache import cache
Expand Down Expand Up @@ -102,6 +103,35 @@ def test_files(self):
obj4.random.save("random_file", ContentFile("random content")) obj4.random.save("random_file", ContentFile("random content"))
self.assertTrue(obj4.random.name.endswith("/random_file")) self.assertTrue(obj4.random.name.endswith("/random_file"))


def test_file_object(self):
# Create sample file
temp_storage.save('tests/example.txt', ContentFile('some content'))

# Load it as python file object
file_obj = open(temp_storage.path('tests/example.txt'))

# Save it using storage and read its content
temp_storage.save('tests/file_obj', file_obj)
self.assertTrue(temp_storage.exists('tests/file_obj'))
self.assertEqual(
temp_storage.open('tests/file_obj').read(),
'some content')


def test_stringio(self):
# Test passing StringIO instance as content argument to save
output = StringIO.StringIO()
output.write('content')
output.seek(0)

# Save it and read written file
temp_storage.save('tests/stringio', output)
self.assertTrue(temp_storage.exists('tests/stringio'))
self.assertEqual(
temp_storage.open('tests/stringio').read(),
'content')




class FileTests(unittest.TestCase): class FileTests(unittest.TestCase):
def test_context_manager(self): def test_context_manager(self):
Expand Down

0 comments on commit 664855b

Please sign in to comment.