You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ResourceControllerV2列举IBM Cloud资源时分页功能失效问题

问题原因

分页失效的核心原因是参数传错:list_resource_instances 接口的start参数仅接收分页token值,不接收完整的next_url字符串。你把完整URL直接传入后,SDK无法识别这个无效参数值,会默认按无分页参数的逻辑返回第一页数据,所以永远只能拿到第一页内容。
另外原代码的循环逻辑也有缺陷:用rows_count > 0作为循环条件无法正确识别最后一页,最后一页的next_url为空时继续发请求会触发报错甚至死循环。

修正要点
  • 不要直接传入完整next_url,需要从返回的next_url中解析出查询参数里的start对应的token值,再传给接口的start参数
  • 不要用rows_count判断是否终止循环,改为判断next_url是否为空:为空就代表已经到最后一页,直接终止循环即可
  • 用Python标准库urllib.parse处理URL解析即可,不需要额外安装第三方依赖
修正后可运行代码
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_platform_services import ResourceControllerV2
from urllib.parse import urlparse, parse_qs

# 替换为你自己的配置值
RESOURCE_CONTROLLER_APIKEY = "你的IBM Cloud IAM API密钥"
RESOURCE_CONTROLLER_URL = "https://resource-controller.cloud.ibm.com"

try:
    # 初始化鉴权与服务客户端
    auth = IAMAuthenticator(RESOURCE_CONTROLLER_APIKEY)
    service = ResourceControllerV2(authenticator=auth)
    service.set_service_url(RESOURCE_CONTROLLER_URL)

    # 发起第一页请求
    resp = service.list_resource_instances().get_result()

    while True:
        current_page_resources = resp.get("resources", [])
        print(f"当前页资源条数:{len(current_page_resources)}")

        # 遍历当前页筛选COS实例
        for resource in current_page_resources:
            resource_type = resource["id"].split(":")[4]
            if resource_type == "cloud-object-storage":
                instance_name = resource["name"]
                instance_id = resource["guid"]
                print(f"找到COS实例 | ID:{instance_id} | 名称:{instance_name}")

        # 检查是否存在下一页
        next_url = resp.get("next_url")
        if not next_url:
            print("所有资源拉取完成")
            break

        # 从next_url中解析分页start token
        parsed_url = urlparse(next_url)
        query_args = parse_qs(parsed_url.query)
        start_token = query_args["start"][0]

        # 传入token拉取下一页
        resp = service.list_resource_instances(start=start_token).get_result()

except Exception as e:
    print(f"运行出错:{e}")
    exit(1)
更简便的写法(新版SDK支持)

如果你使用的是0.18.0以上版本的ibm-platform-services SDK,官方已经封装好了自动分页的Pager类,不需要手动解析URL处理翻页逻辑:

from ibm_platform_services.resource_controller_v2 import ResourceInstancesPager

# 初始化服务客户端的逻辑和上面一致
pager = ResourceInstancesPager(client=service)
# 直接获取所有页的资源
all_resources = pager.get_all()

# 后续直接遍历all_resources筛选COS实例即可
for resource in all_resources:
    resource_type = resource["id"].split(":")[4]
    if resource_type == "cloud-object-storage":
        print(f"找到COS实例 | ID:{resource['guid']} | 名称:{resource['name']}")

内容的提问来源于stack exchange,提问作者John Croson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 01:54:34