如何使用msgraph Python SDK获取OneDrive for Business指定文件夹文件
解决OneDrive for Business文件访问问题
1. 先确认SDK版本匹配
Microsoft Graph Python SDK v5和旧版本API结构差异极大,你碰到的root/items属性不存在的问题,基本是版本不兼容导致的。以下是v5版本的正确调用方式:
方式一:直接获取用户默认OneDrive(推荐)
用户的「我的文件」对应默认OneDrive,无需枚举驱动器选ID,直接调用:
# 获取根目录下所有子项 root_children = self.client.users.by_user_id(user_id).drive.root.children.get() # 筛选出"Documents"文件夹 documents_folder = next(item for item in root_children.value if item.name == "Documents")
方式二:指定Drive ID访问
如果坚持用已获取的OneDrive ID(注意别用PersonalCache的ID),代码如下:
root_children = self.client.users.by_user_id(user_id).drives.by_drive_id(drive_id).root.children.get() documents_folder = next(item for item in root_children.value if item.name == "Documents")
方式三:通过路径直接定位(最高效)
不用遍历子项,直接通过路径获取目标文件夹:
# 默认OneDrive下的Documents documents_folder = self.client.users.by_user_id(user_id).drive.items.by_path("/Documents").get() # 指定Drive ID的情况 documents_folder = self.client.users.by_user_id(user_id).drives.by_drive_id(drive_id).items.by_path("/Documents").get()
2. 权限与客户端初始化检查
- 确保
Files.ReadWrite.All是应用权限且已完成管理员同意(应用权限必须管理员审批才能生效)。 - 客户端初始化必须用客户端凭据流,示例:
from azure.identity import ClientSecretCredential from msgraph import GraphServiceClient credential = ClientSecretCredential( tenant_id="你的租户ID", client_id="你的应用ID", client_secret="你的应用密钥" ) client = GraphServiceClient(credential, scopes=["https://graph.microsoft.com/.default"])
3. 排除Drive ID错误
你列出的两个驱动器里,PersonalCache是缓存驱动器,不是用户的实际OneDrive,必须使用名为「OneDrive」的驱动器ID,别用错。
内容的提问来源于stack exchange,提问作者Luca
相关产品推荐
相关产品推荐

