使用 ResourceControllerV2 列出 IBM Cloud 资源和分页问题

问题描述 投票:0回答:3

我正在使用 Python ibm-cloud-sdk 尝试迭代特定 IBM Cloud 帐户中的所有资源。我的问题是分页似乎“不适合我”。当我传递“next_url”时,我仍然得到从通话中返回的相同列表。

这是我的测试代码。我成功打印了许多 COS 实例,但我似乎只能打印第一页......也许我已经看这个太久了,只是错过了一些明显的东西......任何人都知道为什么我可以找不到下一页?

try:
    ####### authenticate and set the service url
    auth = IAMAuthenticator(RESOURCE_CONTROLLER_APIKEY)
    service = ResourceControllerV2(authenticator=auth)
    service.set_service_url(RESOURCE_CONTROLLER_URL)

    ####### Retrieve the resource instance listing
    r = service.list_resource_instances().get_result()
    ####### get the row count and resources list
    rows_count = r['rows_count']
    resources = r['resources']

    while rows_count > 0:
        print('Number of rows_count {}'.format(rows_count))

        next_url = r['next_url']

        for i, resource in enumerate(resources):
            type = resource['id'].split(':')[4]
            if type == 'cloud-object-storage':
                instance_name = resource['name']
                instance_id = resource['guid']
                crn = resource['crn']
                print('Found instance id : name - {} : {}'.format(instance_id, instance_name))

        ############### this is SUPPOSED to get the next page
        r = service.list_resource_instances(start=next_url).get_result()
        rows_count = r['rows_count']
        resources = r['resources']

except Exception as e:
    Error = 'Error : {}'.format(e)
    print(Error)
    exit(1)

python ibm-cloud
3个回答
0
投票

查看用于列出资源实例的 API 文档next_url 的值包括 URL 路径和 start 参数(包括其启动标记)。

要检索下一页,您只需传入参数 start 并以令牌作为值。恕我直言,这并不理想。

我通常不使用 SDK,而只是使用简单的 Python 请求。然后,我可以使用端点(基本)URI + next_url 作为完整 URI。

如果您坚持使用 SDK,请使用 urllib.parse 提取查询参数。未经测试,但类似:

from urllib.parse import urlparse,parse_qs
o=urlparse(next_url)
q=parse_qs(o.query)
r = service.list_resource_instances(start=q['start'][0]).get_result()

0
投票

您可以使用搜索 API 而不是资源控制器来列出您帐户中的资源吗?搜索索引正是针对该操作而设置的,而从资源控制器对结果进行分页似乎更加暴力。

https://cloud.ibm.com/apidocs/search#search


0
投票

这个答案有点晚了,但是 Platform Services Python SDK 中的资源控制器服务已更新,添加了一些与分页相关的附加便利功能。

具体来说,您可以实例化并使用 ResourceInstancesPager 类一次检索一页的项目,而不是直接调用

list_resource_instances()
操作,同时避免从“next_url”响应属性中检索“start”参数值等细节.

您可以在此处找到示例。

© www.soinside.com 2019 - 2024. All rights reserved.