用于连接到One Drive for Business的Python脚本



我正试图使用此脚本连接到One drive for Business。

import os
import requests
import json
import msal

CLIENT_ID = 'xx'
TENANT_ID = 'xx'
AUTHORITY_URL = 'https://login.microsoftonline.com/{}'.format(TENANT_ID)
RESOURCE_URL = 'https://graph.microsoft.com/'
API_VERSION = 'v1.0'
USERNAME = 'xx' #Office365 user's account username
PASSWORD = 'xx'
SCOPES = ['Sites.ReadWrite.All','Files.ReadWrite.All'] # Add other scopes/permissions as needed.
#Creating a public client app, Aquire a access token for the user and set the header for API calls
cognos_to_onedrive = msal.PublicClientApplication(CLIENT_ID, authority=AUTHORITY_URL)
token = cognos_to_onedrive.acquire_token_by_username_password(USERNAME,PASSWORD,SCOPES)
print(token)
headers = {'Authorization': 'Bearer {}'.format(token['access_token'])}
#Looping through the files inside the source directory
for root, dirs, files in os.walk('C:/Users/Lenovo/Documents/securepass'):
for file_name in files:
file_path = os.path.join(root,file_name)
file_size = os.stat(file_path).st_size
file_data = open(file_path, 'rb')
if file_size < 4100000:

#Perform simple upload to the OneDrive API
r = requests.put('https://graph.microsoft.com/v1.0/users/xxx(userame?)/drive/root:/DropFileIn'+"/"+file_name+":/content", data=file_data, headers=headers)

我已在清单中注册了一个启用应用程序的隐式流,并授予它Sites.AllRead权限。在使用它时,我被要求使用2FA,可能是因为Azure认为这是一种有风险的登录。我没有授予应用程序权限,而是授予应用程序应用程序权限并在应用程序清单中启用"allowPublicClient": true,。我的问题是,如何指定我需要连接到哪个OneDrive?我的意思是,我想连接哪个用户的OneDrive,我该如何在代码中指定它?我需要对该用户进行身份验证吗?

以上代码来自

Microsoft Graph OneDrive根资源

您可以使用以下Graph API请求与特定的OneDrive进行交互。

  1. /drives-列出经过身份验证的可用驱动器资源用户
  2. /drives/{drive-id}通过其ID访问特定驱动器

最新更新