Skip to content

Commit a11d831

Browse files
authored
Allow for uploading metadata with GCS Hook Upload (#22058)
1 parent c1faaf3 commit a11d831

File tree

2 files changed

+14
-2
lines changed
  • airflow/providers/google/cloud/hooks
  • tests/providers/google/cloud/hooks

2 files changed

+14
-2
lines changed

airflow/providers/google/cloud/hooks/gcs.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -447,6 +447,7 @@ def upload(
447447
chunk_size: Optional[int] = None,
448448
timeout: Optional[int] = DEFAULT_TIMEOUT,
449449
num_max_attempts: int = 1,
450+
metadata: Optional[dict] = None,
450451
) -> None:
451452
"""
452453
Uploads a local file or file data as string or bytes to Google Cloud Storage.
@@ -461,6 +462,7 @@ def upload(
461462
:param chunk_size: Blob chunk size.
462463
:param timeout: Request timeout in seconds.
463464
:param num_max_attempts: Number of attempts to try to upload the file.
465+
:param metadata: The metadata to be uploaded with the file.
464466
"""
465467

466468
def _call_with_retry(f: Callable[[], None]) -> None:
@@ -493,6 +495,10 @@ def _call_with_retry(f: Callable[[], None]) -> None:
493495
client = self.get_conn()
494496
bucket = client.bucket(bucket_name)
495497
blob = bucket.blob(blob_name=object_name, chunk_size=chunk_size)
498+
499+
if metadata:
500+
blob.metadata = metadata
501+
496502
if filename and data:
497503
raise ValueError(
498504
"'filename' and 'data' parameter provided. Please "

tests/providers/google/cloud/hooks/test_gcs.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -789,15 +789,21 @@ def tearDown(self):
789789
def test_upload_file(self, mock_service):
790790
test_bucket = 'test_bucket'
791791
test_object = 'test_object'
792+
metadata = {'key1': 'val1', 'key2': 'key2'}
792793

793-
upload_method = mock_service.return_value.bucket.return_value.blob.return_value.upload_from_filename
794+
bucket_mock = mock_service.return_value.bucket
795+
blob_object = bucket_mock.return_value.blob
794796

795-
self.gcs_hook.upload(test_bucket, test_object, filename=self.testfile.name)
797+
upload_method = blob_object.return_value.upload_from_filename
798+
799+
self.gcs_hook.upload(test_bucket, test_object, filename=self.testfile.name, metadata=metadata)
796800

797801
upload_method.assert_called_once_with(
798802
filename=self.testfile.name, content_type='application/octet-stream', timeout=60
799803
)
800804

805+
self.assertEqual(metadata, blob_object.return_value.metadata)
806+
801807
@mock.patch(GCS_STRING.format('GCSHook.get_conn'))
802808
def test_upload_file_gzip(self, mock_service):
803809
test_bucket = 'test_bucket'

0 commit comments

Comments
 (0)