13
13
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
14
# See the License for the specific language governing permissions and
15
15
# limitations under the License.
16
-
17
- # [START all]
18
-
19
16
"""Command-line sample application for listing all objects in a bucket using
20
17
the Cloud Storage API.
21
18
30
27
import json
31
28
32
29
from googleapiclient import discovery
30
+
33
31
from oauth2client .client import GoogleCredentials
34
32
35
33
36
- def main ( bucket ):
37
- # [START list_bucket]
34
+ def create_service ( ):
35
+ """Creates the service object for calling the Cloud Storage API."""
38
36
# Get the application default credentials. When running locally, these are
39
37
# available after running `gcloud init`. When running on compute
40
38
# engine, these are available from the environment.
@@ -44,26 +42,41 @@ def main(bucket):
44
42
# the 'storage' service, at version 'v1'.
45
43
# You can browse other available api services and versions here:
46
44
# 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 ()
48
51
49
52
# Make a request to buckets.get to retrieve a list of objects in the
50
53
# specified bucket.
51
54
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 ()
55
61
56
62
# Create a request to objects.list to retrieve a list of objects.
57
63
fields_to_return = \
58
64
'nextPageToken,items(name,size,contentType,metadata(my-key))'
59
65
req = service .objects ().list (bucket = bucket , fields = fields_to_return )
60
66
67
+ all_objects = []
61
68
# If you have too many items to list in one request, list_next() will
62
69
# automatically handle paging with the pageToken.
63
70
while req :
64
71
resp = req .execute ()
65
- print ( json . dumps (resp , indent = 2 ))
72
+ all_objects . extend (resp . get ( 'items' , [] ))
66
73
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 ))
67
80
68
81
69
82
if __name__ == '__main__' :
@@ -75,4 +88,3 @@ def main(bucket):
75
88
args = parser .parse_args ()
76
89
77
90
main (args .bucket )
78
- # [END all]
0 commit comments