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

如何使用Microsoft Graph SDK for Python通过SharePoint站点名称获取站点ID

如何使用Microsoft Graph SDK for Python通过SharePoint站点名称获取站点ID

我懂你现在的需求——之前用PowerShell能通过SharePoint站点名称拿到站点ID,现在想换成Python的Microsoft Graph SDK来做,这样就能继续调用后续的接口(比如获取站点驱动器)对吧?其实这个操作和你PowerShell里的逻辑完全一致,只是换成SDK的封装写法而已,我来给你一步步讲清楚怎么实现:

核心逻辑对应

你在PowerShell里构造的请求是通过/sites/租户域名:/sites/站点名称这个特殊路径查询站点信息并指定返回id字段,在Python的Graph SDK里,这个逻辑对应GraphServiceClient的sites.get_by_path方法,SDK会帮你自动构造正确的请求URL,不用手动拼接字符串。

修改后的完整代码

把你原来的代码调整一下,加入获取站点ID的逻辑,同时规范异步代码的写法:

import asyncio

from azure.identity.aio import ClientSecretCredential
from msgraph import GraphServiceClient

# 替换成你的实际配置
tenant_id="你的租户ID"
client_id="你的客户端ID"
client_secret="你的客户端密钥"

credential = ClientSecretCredential(tenant_id, client_id, client_secret)
scopes = ['https://graph.microsoft.com/.default']

client = GraphServiceClient(credentials=credential, scopes=scopes)

sharepoint_tenant = "foobar365.sharepoint.com"
site_name = "someTestSPsite"

async def get_site_info():
    # 通过站点名称获取站点ID,完全对应你PowerShell的请求逻辑
    site = await client.sites.get_by_path(
        path=f"/sites/{site_name}",
        host_name=sharepoint_tenant,
        select=["id"]  # 只请求id字段,减少返回数据量
    )
    site_id = site.id
    print(f"获取到的站点ID:{site_id}")

    # 用拿到的站点ID调用驱动器接口
    drives = await client.sites.by_site_id(site_id).drives.get()
    print(drives)

# 执行异步函数
asyncio.run(get_site_info())

关键细节说明

  • get_by_path方法:这个方法是SDK对/sites/{host}:/{path}这种特殊站点查询路径的封装,参数里的host_name是你的SharePoint租户域名,path就是站点的相对路径(也就是/sites/你的站点名称)
  • select=["id"]:和你PowerShell里的$select=id作用完全一样,只让Graph API返回id字段,避免返回多余数据,提升请求效率
  • 异步处理:因为使用了azure.identity.aio的异步凭证,所以所有SDK的调用都需要用await,把逻辑封装在异步函数里再用asyncio.run执行是更规范的写法,避免异步嵌套的问题

注意事项

要确保你的Azure AD应用注册已经拥有Sites.Read.All(或者更具体的站点读取权限),不然会返回权限不足的错误,这和你PowerShell里使用的权限要求是一致的。

备注:内容来源于stack exchange,提问作者Vitamin C

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 09:19:30