如何通过ID而非名称从Google Cloud Storage获取对象?
Got it, let's tackle this problem! First, let's clarify a key detail about Google Cloud Storage (GCS) object IDs: an object's unique ID is actually a structured string that encodes both the bucket name and object name you need for the standard API methods. Typically, it looks like projects/_/buckets/{BUCKET_NAME}/objects/{OBJECT_NAME} (or sometimes the shorter {BUCKET_NAME}/{OBJECT_NAME} format).
Here's how you can use this to fetch your object:
Step 1: Parse the Object ID
Extract the bucket name and object name from the ID string:
- For an ID like
projects/_/buckets/my-bucket/objects/reports/2024/Q1/sales.csv:- Bucket name:
my-bucket - Object name:
reports/2024/Q1/sales.csv
- Bucket name:
Step 2: Use the Standard objects.get Method
Once you have those two values, you can use the regular objects.get API exactly as documented. Here are examples for common use cases:
REST API Request
Send a GET request to the endpoint, replacing placeholders with your parsed values:
https://storage.googleapis.com/storage/v1/b/{BUCKET_NAME}/o/{OBJECT_NAME}
(Remember to URL-encode the object name if it contains special characters like slashes or spaces.)
Python Client Library Example
from google.cloud import storage def fetch_object_by_id(object_id): # Parse the ID to extract bucket and object name id_parts = object_id.split("/") bucket_name = id_parts[3] object_name = "/".join(id_parts[5:]) # Initialize GCS client and fetch the object storage_client = storage.Client() bucket = storage_client.bucket(bucket_name) blob = bucket.blob(object_name) # Get metadata or download content as needed object_metadata = blob.metadata object_content = blob.download_as_bytes() return object_metadata, object_content
Alternative: Use the Full ID Directly
Some GCS API endpoints accept the complete object ID as the object parameter. You can try passing the full ID directly to objects.get without parsing it first. For example:
GET https://storage.googleapis.com/storage/v1/b/{BUCKET_NAME}/o/{FULL_OBJECT_ID}
Note: You'll need to URL-encode the full ID if it contains special characters to avoid request errors.
Why This Works
GCS doesn't have a dedicated "get by ID" endpoint, but since the object ID is a unique, structured identifier that directly maps to the bucket and object name, parsing it gives you all the parameters required for the standard API methods. This approach is reliable and aligns with GCS's core object addressing model.
内容的提问来源于stack exchange,提问作者acidboy

