Skip to content

Commit

Permalink
Add open method on S3Boto3StorageFile with test
Browse files Browse the repository at this point in the history
  • Loading branch information
Aaron committed Mar 28, 2023
1 parent 90e2e78 commit 7b76dae
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
14 changes: 13 additions & 1 deletion storages/backends/s3boto3.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,10 @@ class S3Boto3StorageFile(CompressedFileMixin, File):
order to properly write the file to S3. Be sure to close the file
in your application.
"""

def __init__(self, name, mode, storage, buffer_size=None):
self._initialize(name, mode, storage, buffer_size)

def _initialize(self, name, mode, storage, buffer_size=None):
if 'r' in mode and 'w' in mode:
raise ValueError("Can't combine 'r' and 'w' in mode.")
self._storage = storage
Expand Down Expand Up @@ -224,6 +226,16 @@ def _create_empty_on_close(self):
else:
raise

def open(self, mode=None):
if not self.closed:
# keeping it consistent with django default file behaviour
self.seek(0)
elif mode != self._mode:
self._initialize(self.name, mode, self._storage, self.buffer_size)
else:
raise ValueError("The file cannot be reopened.")
return self

def close(self):
if self._is_dirty:
self._flush_write_buffer()
Expand Down
19 changes: 19 additions & 0 deletions tests/test_s3boto3.py
Original file line number Diff line number Diff line change
Expand Up @@ -767,6 +767,25 @@ def test_override_init_argument(self):
storage = s3boto3.S3Boto3Storage(location='foo2')
self.assertEqual(storage.location, 'foo2')

def test_open_file(self):
filename = "file_to_open.txt"
file = self.storage.open(filename, "w")
file.write("foo")
file.close()
file.open()
self.assertEqual(file._mode, "w")
file.close()
file.open("r")
self.assertEqual(file._mode, "r")
assert(file.read(), "foo")
file.close()
file.open("a")
file.write("bar")
file.close()
file.open("r")
self.assertEqual(file.read(), "foobar")
file.close()


class S3StaticStorageTests(TestCase):
def setUp(self):
Expand Down

0 comments on commit 7b76dae

Please sign in to comment.