Skip to content
This repository was archived by the owner on Dec 31, 2023. It is now read-only.

Commit db0404c

Browse files
authored
docs(samples): Adding pagination sample. (#78)
1 parent 7c32037 commit db0404c

File tree

3 files changed

+116
-1
lines changed

3 files changed

+116
-1
lines changed

samples/snippets/quickstart.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,9 +73,14 @@ def list_all_instances(
7373
iterable collections of Instance objects as values.
7474
"""
7575
instance_client = compute_v1.InstancesClient()
76-
agg_list = instance_client.aggregated_list(project=project_id)
76+
# Use the `max_results` parameter to limit the number of results that the API returns per response page.
77+
request = compute_v1.AggregatedListInstancesRequest(project=project_id, max_results=5)
78+
agg_list = instance_client.aggregated_list(request=request)
7779
all_instances = {}
7880
print("Instances found:")
81+
# Despite using the `max_results` parameter, you don't need to handle the pagination
82+
# yourself. The returned `AggregatedListPager` object handles pagination
83+
# automatically, returning separated pages as you iterate over the results.
7984
for zone, response in agg_list:
8085
if response.instances:
8186
all_instances[zone] = response.instances

samples/snippets/sample_pagination.py

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
#!/usr/bin/env python
2+
3+
# Copyright 2021 Google LLC
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
# [START compute_images_list_page ]
18+
# [START compute_images_list ]
19+
import google.cloud.compute_v1 as compute_v1
20+
# [END compute_images_list ]
21+
# [END compute_images_list_page ]
22+
23+
24+
# [START compute_images_list ]
25+
def print_images_list(project: str) -> None:
26+
"""
27+
Prints a list of all non-deprecated image names available in given project.
28+
29+
Args:
30+
project: project ID or project number of the Cloud project you want to list images from.
31+
32+
Returns:
33+
None.
34+
"""
35+
images_client = compute_v1.ImagesClient()
36+
# Listing only non-deprecated images to reduce the size of the reply.
37+
images_list_request = compute_v1.ListImagesRequest(project=project, max_results=3,
38+
filter="deprecated.state != DEPRECATED")
39+
40+
# Although the `max_results` parameter is specified in the request, the iterable returned
41+
# by the `list()` method hides the pagination mechanic. The library makes multiple
42+
# requests to the API for you, so you can simply iterate over all the images.
43+
for img in images_client.list(request=images_list_request):
44+
print(f" - {img.name}")
45+
# [END compute_images_list ]
46+
47+
48+
# [START compute_images_list_page ]
49+
def print_images_list_by_page(project: str, page_size: int = 10) -> None:
50+
"""
51+
Prints a list of all non-deprecated image names available in a given project,
52+
divided into pages as returned by the Compute Engine API.
53+
54+
Args:
55+
project: project ID or project number of the Cloud project you want to list images from.
56+
page_size: size of the pages you want the API to return on each call.
57+
58+
Returns:
59+
None.
60+
"""
61+
images_client = compute_v1.ImagesClient()
62+
# Listing only non-deprecated images to reduce the size of the reply.
63+
images_list_request = compute_v1.ListImagesRequest(project=project, max_results=page_size,
64+
filter="deprecated.state != DEPRECATED")
65+
66+
# Use the `pages` attribute of returned iterable to have more granular control of
67+
# iteration over paginated results from the API. Each time you want to access the
68+
# next page, the library retrieves that page from the API.
69+
for page_num, page in enumerate(images_client.list(request=images_list_request).pages, start=1):
70+
print(f"Page {page_num}: ")
71+
for img in page.items:
72+
print(f" - {img.name}")
73+
# [END compute_images_list_page ]
74+
75+
76+
if __name__ == '__main__':
77+
print("=================== Flat list of images ===================")
78+
print_images_list('windows-sql-cloud')
79+
print("================= Paginated list of images ================")
80+
print_images_list_by_page('windows-sql-cloud', 5)
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Copyright 2021 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
import typing
15+
16+
from sample_pagination import print_images_list, print_images_list_by_page
17+
18+
PROJECT = 'windows-sql-cloud'
19+
20+
21+
def test_pagination(capsys: typing.Any) -> None:
22+
print_images_list(PROJECT)
23+
out, _ = capsys.readouterr()
24+
assert(len(out.splitlines()) > 2)
25+
26+
27+
def test_pagination_page(capsys: typing.Any) -> None:
28+
print_images_list_by_page(PROJECT, 2)
29+
out, _ = capsys.readouterr()
30+
assert("Page 2" in out)

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy