diff --git a/storages/backends/s3.py b/storages/backends/s3.py index 3edc3c9a..66f7a0cf 100644 --- a/storages/backends/s3.py +++ b/storages/backends/s3.py @@ -535,7 +535,12 @@ def listdir(self, name): def size(self, name): name = self._normalize_name(clean_name(name)) - return self.bucket.Object(name).content_length + try: + return self.bucket.Object(name).content_length + except ClientError as err: + if err.response["ResponseMetadata"]["HTTPStatusCode"] == 404: + raise FileNotFoundError("File does not exist: %s" % name) + raise # Let it bubble up if it was some other error def _get_write_parameters(self, name, content=None): params = self.get_object_parameters(name) diff --git a/tests/test_s3.py b/tests/test_s3.py index 7d1e7f5f..6f43980a 100644 --- a/tests/test_s3.py +++ b/tests/test_s3.py @@ -647,6 +647,17 @@ def test_storage_size(self): name = "file.txt" self.assertEqual(self.storage.size(name), obj.content_length) + def test_storage_size_not_exists(self): + self.storage.bucket.Object.side_effect = ClientError( + {"Error": {}, "ResponseMetadata": {"HTTPStatusCode": 404}}, + "HeadObject", + ) + name = "file.txt" + with self.assertRaisesMessage( + FileNotFoundError, "File does not exist: file.txt" + ): + self.storage.size(name) + def test_storage_mtime(self): # Test both USE_TZ cases for use_tz in (True, False):