Skip to content

Commit 79d27da

Browse files
authored
fix: allow metadata keys to be cleared (#383)
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
1 parent f85af9b commit 79d27da

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

google/cloud/storage/blob.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3620,13 +3620,16 @@ def metadata(self):
36203620
def metadata(self, value):
36213621
"""Update arbitrary/application specific metadata for the object.
36223622
3623+
Values are stored to GCS as strings. To delete a key, set its value to
3624+
None and call blob.patch().
3625+
36233626
See https://cloud.google.com/storage/docs/json_api/v1/objects
36243627
36253628
:type value: dict
36263629
:param value: The blob metadata to set.
36273630
"""
36283631
if value is not None:
3629-
value = {k: str(v) for k, v in value.items()}
3632+
value = {k: str(v) if v is not None else None for k, v in value.items()}
36303633
self._patch_property("metadata", value)
36313634

36323635
@property

tests/system/test_system.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -874,6 +874,19 @@ def test_write_metadata(self):
874874
blob.content_type = "image/png"
875875
self.assertEqual(blob.content_type, "image/png")
876876

877+
metadata = {"foo": "Foo", "bar": "Bar"}
878+
blob.metadata = metadata
879+
blob.patch()
880+
blob.reload()
881+
self.assertEqual(blob.metadata, metadata)
882+
883+
# Ensure that metadata keys can be deleted by setting equal to None.
884+
new_metadata = {"foo": "Foo", "bar": None}
885+
blob.metadata = new_metadata
886+
blob.patch()
887+
blob.reload()
888+
self.assertEqual(blob.metadata, {"foo": "Foo"})
889+
877890
def test_direct_write_and_read_into_file(self):
878891
blob = self.bucket.blob("MyBuffer")
879892
file_contents = b"Hello World"

0 commit comments

Comments
 (0)