From 5207559f92013ebd3253c8aaa45a568800dd31d8 Mon Sep 17 00:00:00 2001 From: Jerjou Cheng Date: Mon, 14 Mar 2016 15:29:19 -0700 Subject: [PATCH] Refactor storage sample for better code-inclusion --- storage/api/list_objects.py | 34 +++++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/storage/api/list_objects.py b/storage/api/list_objects.py index 7226d4bd7328..ca0d80f0e10c 100644 --- a/storage/api/list_objects.py +++ b/storage/api/list_objects.py @@ -13,9 +13,6 @@ # 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. - -# [START all] - """Command-line sample application for listing all objects in a bucket using the Cloud Storage API. @@ -30,11 +27,12 @@ import json from googleapiclient import discovery + from oauth2client.client import GoogleCredentials -def main(bucket): - # [START list_bucket] +def create_service(): + """Creates the service object for calling the Cloud Storage API.""" # Get the application default credentials. When running locally, these are # available after running `gcloud init`. When running on compute # engine, these are available from the environment. @@ -44,26 +42,41 @@ def main(bucket): # the 'storage' service, at version 'v1'. # You can browse other available api services and versions here: # https://developers.google.com/api-client-library/python/apis/ - service = discovery.build('storage', 'v1', credentials=credentials) + return discovery.build('storage', 'v1', credentials=credentials) + + +def get_bucket_metadata(bucket): + """Retrieves metadata about the given bucket.""" + service = create_service() # Make a request to buckets.get to retrieve a list of objects in the # specified bucket. req = service.buckets().get(bucket=bucket) - resp = req.execute() - print(json.dumps(resp, indent=2)) - # [END list_bucket] + return req.execute() + + +def list_bucket(bucket): + """Returns a list of metadata of the objects within the given bucket.""" + service = create_service() # Create a request to objects.list to retrieve a list of objects. fields_to_return = \ 'nextPageToken,items(name,size,contentType,metadata(my-key))' req = service.objects().list(bucket=bucket, fields=fields_to_return) + all_objects = [] # If you have too many items to list in one request, list_next() will # automatically handle paging with the pageToken. while req: resp = req.execute() - print(json.dumps(resp, indent=2)) + all_objects.extend(resp.get('items', [])) req = service.objects().list_next(req, resp) + return all_objects + + +def main(bucket): + print(json.dumps(get_bucket_metadata(bucket), indent=2)) + print(json.dumps(list_bucket(bucket), indent=2)) if __name__ == '__main__': @@ -75,4 +88,3 @@ def main(bucket): args = parser.parse_args() main(args.bucket) -# [END all]