Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions samples/snippets/snippets_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
import storage_list_soft_deleted_objects
import storage_make_public
import storage_move_file
import storage_move_file_atomically
import storage_object_get_kms_key
import storage_remove_bucket_label
import storage_remove_cors_configuration
Expand Down Expand Up @@ -1037,3 +1038,20 @@ def test_storage_restore_soft_deleted_object(test_soft_delete_enabled_bucket, ca
# Verify the restoration
blob = test_soft_delete_enabled_bucket.get_blob(blob_name)
assert blob is not None


def test_move_object(test_blob):
bucket = test_blob.bucket
try:
bucket.delete_blob("test_move_blob_atomic")
except google.cloud.exceptions.NotFound:
print(f"test_move_blob_atomic not found in bucket {bucket.name}")

storage_move_file_atomically.move_object(
bucket.name,
test_blob.name,
"test_move_blob_atomic",
)

assert bucket.get_blob("test_move_blob_atomic") is not None
assert bucket.get_blob(test_blob.name) is None
54 changes: 54 additions & 0 deletions samples/snippets/storage_move_file_atomically.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#!/usr/bin/env python

# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys

# [START storage_move_object]
from google.cloud import storage


def move_object(bucket_name: str, blob_name: str, new_blob_name: str) -> None:
"""Moves a blob to a new name within the same bucket using the move API."""
# The name of your GCS bucket
# bucket_name = "your-bucket-name"

# The name of your GCS object to move
# blob_name = "your-file-name"

# The new name of the GCS object
# new_blob_name = "new-file-name"

storage_client = storage.Client()

bucket = storage_client.bucket(bucket_name)
blob_to_move = bucket.blob(blob_name)

# Use move_blob to perform an efficient, server-side move.
moved_blob = bucket.move_blob(
blob=blob_to_move, new_name=new_blob_name
)

print(f"Blob {blob_to_move.name} has been moved to {moved_blob.name}.")


# [END storage_move_object]

if __name__ == "__main__":
move_object(
bucket_name=sys.argv[1],
blob_name=sys.argv[2],
new_blob_name=sys.argv[3],
)