如何使用MS Graph Python SDK获取OneDrive账户所有文件?
使用MS Graph Python SDK拉取OneDrive商业账户所有文件
核心要点
- 权限前置配置:服务账户需在Azure AD中添加
Files.Read.All应用权限,并完成管理员同意,否则会因权限不足调用失败。 - 精准定位OneDrive:用
drive端点获取用户默认OneDrive(drives返回用户所有驱动器,非默认场景才需要)。 - 处理分页结果:OneDrive返回数据默认分页,需循环拉取所有页面的文件。
完整代码示例
import asyncio from msgraph import GraphServiceClient from azure.identity import ClientSecretCredential microsoft_tenant_id = '123abc' client_id = '123abc' client_secret = '123abc' # 应用权限需提前在Azure AD配置并完成管理员授权 SCOPES = ['https://graph.microsoft.com/.default'] credential = ClientSecretCredential(microsoft_tenant_id, client_id, client_secret) graph_client = GraphServiceClient(credential, SCOPES) user_id = 'myemail@companyname.com' async def get_all_onedrive_files(): all_files = [] # 获取用户默认OneDrive根目录的子项(含文件和文件夹) drive_items_page = await graph_client.users.by_user_id(user_id).drive.root.children.get() # 收集第一页数据 if drive_items_page.value: all_files.extend(drive_items_page.value) # 循环拉取后续分页数据 while drive_items_page.odata_next_link: # 提取分页token继续请求 skip_token = drive_items_page.odata_next_link.split('$skipToken=')[1] drive_items_page = await graph_client.users.by_user_id(user_id).drive.root.children.get(skip_token=skip_token) if drive_items_page.value: all_files.extend(drive_items_page.value) # 输出文件信息示例 for item in all_files: item_type = "文件夹" if hasattr(item, 'folder') else "文件" print(f"名称: {item.name}, 类型: {item_type}, ID: {item.id}") return all_files if __name__ == "__main__": asyncio.run(get_all_onedrive_files())
关键代码说明
graph_client.users.by_user_id(user_id).drive.root.children.get():直接请求用户OneDrive根目录下的所有子资源。- 分页逻辑:通过
odata_next_link判断是否存在下一页,提取skipToken参数发起后续请求,确保获取全部文件。 - 资源类型区分:用
hasattr(item, 'folder')判断当前资源是文件还是文件夹。
问题排查
- 权限报错:检查Azure AD中服务账户的应用权限是否已添加
Files.Read.All并完成管理员同意。 - 方法不存在:执行
pip install --upgrade msgraph-core msgraph-sdk更新到最新版SDK。
内容的提问来源于stack exchange,提问作者WHOATEMYNOODLES
相关产品推荐
相关产品推荐

