Skip to content

Commit

Permalink
fix: allow metadata keys to be cleared (#383)
Browse files Browse the repository at this point in the history
Metadata keys can be cleared in the JSON API by setting the value
to null; however this doesn't currently work through this library.
This PR allows users to clear metadata keys by setting the value
to None and documents how users should do this.

Fixes #381
  • Loading branch information
tritone authored Feb 17, 2021
1 parent f85af9b commit 79d27da
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
5 changes: 4 additions & 1 deletion google/cloud/storage/blob.py
Original file line number Diff line number Diff line change
Expand Up @@ -3620,13 +3620,16 @@ def metadata(self):
def metadata(self, value):
"""Update arbitrary/application specific metadata for the object.
Values are stored to GCS as strings. To delete a key, set its value to
None and call blob.patch().
See https://cloud.google.com/storage/docs/json_api/v1/objects
:type value: dict
:param value: The blob metadata to set.
"""
if value is not None:
value = {k: str(v) for k, v in value.items()}
value = {k: str(v) if v is not None else None for k, v in value.items()}
self._patch_property("metadata", value)

@property
Expand Down
13 changes: 13 additions & 0 deletions tests/system/test_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -874,6 +874,19 @@ def test_write_metadata(self):
blob.content_type = "image/png"
self.assertEqual(blob.content_type, "image/png")

metadata = {"foo": "Foo", "bar": "Bar"}
blob.metadata = metadata
blob.patch()
blob.reload()
self.assertEqual(blob.metadata, metadata)

# Ensure that metadata keys can be deleted by setting equal to None.
new_metadata = {"foo": "Foo", "bar": None}
blob.metadata = new_metadata
blob.patch()
blob.reload()
self.assertEqual(blob.metadata, {"foo": "Foo"})

def test_direct_write_and_read_into_file(self):
blob = self.bucket.blob("MyBuffer")
file_contents = b"Hello World"
Expand Down

0 comments on commit 79d27da

Please sign in to comment.