Skip to content

Commit

Permalink
[s3] catch 404 when deleting objects (#1201)
Browse files Browse the repository at this point in the history
  • Loading branch information
jschneier authored Dec 22, 2022
1 parent 7ee3aaa commit 4ad22c3
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
16 changes: 12 additions & 4 deletions storages/backends/s3boto3.py
Original file line number Diff line number Diff line change
Expand Up @@ -446,16 +446,24 @@ def _save(self, name, content):
return cleaned_name

def delete(self, name):
name = self._normalize_name(clean_name(name))
self.bucket.Object(name).delete()
try:
name = self._normalize_name(clean_name(name))
self.bucket.Object(name).delete()
except ClientError as err:
if err.response['ResponseMetadata']['HTTPStatusCode'] == 404:
# Not an error to delete something that does not exist
return

# Some other error was encountered. Re-raise it
raise

def exists(self, name):
name = self._normalize_name(clean_name(name))
try:
self.connection.meta.client.head_object(Bucket=self.bucket_name, Key=name)
return True
except ClientError as error:
if error.response['ResponseMetadata']['HTTPStatusCode'] == 404:
except ClientError as err:
if err.response['ResponseMetadata']['HTTPStatusCode'] == 404:
return False

# Some other error was encountered. Re-raise it.
Expand Down
18 changes: 18 additions & 0 deletions tests/test_s3boto3.py
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,24 @@ def test_storage_delete(self):
self.storage.bucket.Object.assert_called_with('path/to/file.txt')
self.storage.bucket.Object.return_value.delete.assert_called_with()

def test_storage_delete_does_not_exist(self):
self.storage.bucket.Object('file.txt').delete.side_effect = ClientError(
{'Error': {}, 'ResponseMetadata': {'HTTPStatusCode': 404}},
'DeleteObject',
)
self.storage.delete('file.txt')
# No problem

def test_storage_delete_other_error_reraise(self):
self.storage.bucket.Object('file.txt').delete.side_effect = ClientError(
{'Error': {}, 'ResponseMetadata': {'HTTPStatusCode': 403}},
'DeleteObject',
)
with self.assertRaises(ClientError) as cm:
self.storage.delete('file.txt')

self.assertEqual(cm.exception.response['ResponseMetadata']['HTTPStatusCode'], 403)

def test_storage_listdir_base(self):
# Files:
# some/path/1.txt
Expand Down

0 comments on commit 4ad22c3

Please sign in to comment.