1313# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1414# See the License for the specific language governing permissions and
1515# limitations under the License.
16-
17- # [START all]
18-
1916"""Command-line sample application for listing all objects in a bucket using
2017the Cloud Storage API.
2118
3027import json
3128
3229from googleapiclient import discovery
30+
3331from oauth2client .client import GoogleCredentials
3432
3533
36- def main ( bucket ):
37- # [START list_bucket]
34+ def create_service ( ):
35+ """Creates the service object for calling the Cloud Storage API."""
3836 # Get the application default credentials. When running locally, these are
3937 # available after running `gcloud init`. When running on compute
4038 # engine, these are available from the environment.
@@ -44,26 +42,41 @@ def main(bucket):
4442 # the 'storage' service, at version 'v1'.
4543 # You can browse other available api services and versions here:
4644 # https://developers.google.com/api-client-library/python/apis/
47- service = discovery .build ('storage' , 'v1' , credentials = credentials )
45+ return discovery .build ('storage' , 'v1' , credentials = credentials )
46+
47+
48+ def get_bucket_metadata (bucket ):
49+ """Retrieves metadata about the given bucket."""
50+ service = create_service ()
4851
4952 # Make a request to buckets.get to retrieve a list of objects in the
5053 # specified bucket.
5154 req = service .buckets ().get (bucket = bucket )
52- resp = req .execute ()
53- print (json .dumps (resp , indent = 2 ))
54- # [END list_bucket]
55+ return req .execute ()
56+
57+
58+ def list_bucket (bucket ):
59+ """Returns a list of metadata of the objects within the given bucket."""
60+ service = create_service ()
5561
5662 # Create a request to objects.list to retrieve a list of objects.
5763 fields_to_return = \
5864 'nextPageToken,items(name,size,contentType,metadata(my-key))'
5965 req = service .objects ().list (bucket = bucket , fields = fields_to_return )
6066
67+ all_objects = []
6168 # If you have too many items to list in one request, list_next() will
6269 # automatically handle paging with the pageToken.
6370 while req :
6471 resp = req .execute ()
65- print ( json . dumps (resp , indent = 2 ))
72+ all_objects . extend (resp . get ( 'items' , [] ))
6673 req = service .objects ().list_next (req , resp )
74+ return all_objects
75+
76+
77+ def main (bucket ):
78+ print (json .dumps (get_bucket_metadata (bucket ), indent = 2 ))
79+ print (json .dumps (list_bucket (bucket ), indent = 2 ))
6780
6881
6982if __name__ == '__main__' :
@@ -75,4 +88,3 @@ def main(bucket):
7588 args = parser .parse_args ()
7689
7790 main (args .bucket )
78- # [END all]
0 commit comments