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

如何在Azure Python SDK中使用nextLink属性列出所有虚拟机

如何通过Azure Python SDK分页获取所有虚拟机

我尝试用以下代码列出Azure订阅中的所有虚拟机:

from azure.mgmt.compute import ComputeManagementClient
from azure.identity import ClientSecretCredential

credentials = ClientSecretCredential(
    client_id='',
    client_secret='',
    tenant_id=''
)

subID= ''

computer_client = ComputeManagementClient(credentials,subID)
vms = computer_client.virtual_machines.list_all()

for vm in vms:
    print( vm.name )

这段代码能正常运行,但只能列出第一页的虚拟机。我想知道如何获取next_link属性并调用list_next()来获取后续页面的虚拟机,具体语法是什么?

官方文档中提到:

next_link
str
Required
The URI to fetch the next page of VMs. Call ListNext() with this URI to fetch the next page of Virtual Machines.


你可以通过循环检查返回结果的next_link属性,调用virtual_machines.list_next()方法实现分页获取所有虚拟机。修改后的代码如下:

from azure.mgmt.compute import ComputeManagementClient
from azure.identity import ClientSecretCredential

credentials = ClientSecretCredential(
    client_id='',
    client_secret='',
    tenant_id=''
)

subID= ''

computer_client = ComputeManagementClient(credentials, subID)
# 获取第一页结果
response = computer_client.virtual_machines.list_all()

while True:
    # 遍历当前页的虚拟机
    for vm in response:
        print(vm.name)
    # 检查是否存在下一页链接
    if not response.next_link:
        break
    # 获取下一页的虚拟机数据
    response = computer_client.virtual_machines.list_next(response.next_link)

代码说明

  • 首次调用list_all()获取第一页数据,返回的response对象包含当前页的虚拟机列表,以及用于获取下一页的next_link属性
  • 通过while循环持续校验next_link:若该属性不为空,则传入list_next()方法获取下一页数据
  • 当next_link为空时,代表所有页面数据已获取完成,终止循环

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 04:45:32