Skip to content

Commit

Permalink
Allowing files from S3 to be re-opened. Closes #33
Browse files Browse the repository at this point in the history
  • Loading branch information
etianen committed Oct 31, 2016
1 parent 7f3a1d5 commit 0286570
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
20 changes: 18 additions & 2 deletions django_s3_storage/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,22 @@
CONTENT_ENCODING_GZIP = "gzip"


class S3File(File):

"""
A file returned from Amazon S3.
"""

def __init__(self, file, name, storage):
super().__init__(file, name)
self._storage = storage

def open(self, mode=None):
if self.closed:
self.file = self._storage.open(self.name, mode or "rb").file
return super().open(mode)


@deconstructible
class S3Storage(Storage):

Expand Down Expand Up @@ -216,7 +232,7 @@ def _get_metadata(self, name):
}

def _open(self, name, mode="rb"):
if (mode != "rb"):
if mode != "rb":
raise ValueError("S3 files can only be opened in read-only mode")
# Load the key into a temporary file. It would be nice to stream the
# content, but S3 doesn't support seeking, which is sometimes needed.
Expand All @@ -233,7 +249,7 @@ def _open(self, name, mode="rb"):
if key.content_encoding == CONTENT_ENCODING_GZIP:
content = gzip.GzipFile(name, "rb", fileobj=content)
# All done!
return File(content, name)
return S3File(content, name, self)

def _save(self, name, content):
# Calculate the file headers and compression.
Expand Down
6 changes: 6 additions & 0 deletions django_s3_storage/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,12 @@ def assertUrlInaccessible(self, url):
def testOpen(self):
self.assertEqual(self.storage.open(self.upload_path).read(), self.file_contents)

def testReOpen(self):
handle = self.storage.open(self.upload_path)
handle.close()
handle.open()
self.assertEqual(handle.read(), self.file_contents)

def testCannotOpenInWriteMode(self):
with self.assertRaises(ValueError) as cm:
self.storage.open(self.upload_path, "wb")
Expand Down

0 comments on commit 0286570

Please sign in to comment.