Skip to content

Commit

Permalink
Merge pull request #221 from GoogleCloudPlatform/storage-tweaks
Browse files Browse the repository at this point in the history
Refactor storage sample for better code-inclusion
  • Loading branch information
jerjou committed Mar 15, 2016
2 parents d45c1c4 + 5207559 commit 1733e48
Showing 1 changed file with 23 additions and 11 deletions.
34 changes: 23 additions & 11 deletions storage/api/list_objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
Expand All @@ -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__':
Expand All @@ -75,4 +88,3 @@ def main(bucket):
args = parser.parse_args()

main(args.bucket)
# [END all]

0 comments on commit 1733e48

Please sign in to comment.