我见过一些使用 onedrive sdk 的旧方法,似乎这些方法现在不起作用。这是我经过一番研究后得到的方法之一。但它不起作用
import msal
import requests
# Azure AD app credentials
client_id = 'xxx9846xxxx'
client_secret = 'xxxTdxxx'
tenant_id = 'xxx-xxxx'
# Authority URL for your tenant
authority = f'https://login.microsoftonline.com/{tenant_id}'
# Scopes needed for OneDrive file operations
scopes = ['https://graph.microsoft.com/.default']
# Initialize the MSAL ConfidentialClientApplication
app = msal.ConfidentialClientApplication(
client_id,
client_credential=client_secret,
authority=authority
)
# Get the access token
token_response = app.acquire_token_for_client(scopes=scopes)
access_token = token_response.get('access_token')
if not access_token:
raise Exception("Could not acquire access token")
# Define the file to upload
file_path = 'C:/test.csv'
# Microsoft Graph API endpoint for OneDrive (using Application Permissions)
upload_url = 'https://graph.microsoft.com/v1.0/me/drive/root:/Documents/' + file_name + ':/content'
# Open the file in binary mode
with open(file_path, 'rb') as file:
file_content = file.read()
# Make the PUT request to upload the file
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/octet-stream'
}
response = requests.put(upload_url, headers=headers, data=file_content)
# Check if the file upload was successful
if response.status_code == 201:
print(f'File uploaded successfully to OneDrive: {file_name}')
else:
print(f'Error uploading file: {response.status_code}, {response.text}')
我收到以下错误:
上传文件时出错:400, {"error":{"code":"BadRequest","message":"/me 请求仅有效 具有委托身份验证 流。","innerError":{"日期":"2025-01-13T17:06:35","request-id":"5959d049-9ad7-4 ced-b6fc-00ddddd242","客户端请求 ID":"5959d049-9ad7-4ced-b6fc-0079ddddd"}}}
如何解决这个错误?或任何其他上传文件的方式
更新:
我创建了一个新的应用程序注册,支持“任何组织目录中的帐户(任何 Microsoft Entra ID 租户 - 多租户)和个人 Microsoft 帐户(例如 Skype、Xbox)”
这些是我添加的API权限:
更新代码:
import requests
# Replace with your details
client_id = 'xxxxx'
client_secret = 'xxxx'
tenant_id = '052c8b5b-xxxx'
filename = 'C:/test.csv'
onedrive_folder = 'CloudOnly/test'
user_id = 'xxxx-e7d1-44dc-a846-5exxxx'
# Get the access token
url = f'https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token'
data = {
'grant_type': 'client_credentials',
'client_id': client_id,
'client_secret': client_secret,
'scope': 'https://graph.microsoft.com/.default'
}
response = requests.post(url, data=data)
token = response.json().get('access_token')
# Upload the file to OneDrive
headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/octet-stream'
}
file_content = open(filename, 'rb').read()
upload_url = f'https://graph.microsoft.com/v1.0/users/{user_id}/drive/root:/{onedrive_folder}/{filename.split("/")[-1]}:/content'
upload_response = requests.put(upload_url, headers=headers, data=file_content)
if upload_response.status_code == 201:
print('File uploaded successfully!')
else:
print('Error uploading file:', upload_response.json())
但这给了我错误:
上传文件时出错:{'error': {'code': 'BadRequest', 'message': '租户没有 SPO 许可证。', 'innerError': {'date': '2025-01-14T02:15:47', '请求 ID': 'cf70193e-1723-44db-9f5e-xxxxx', '客户端请求 ID': 'cf70193e-1723-44db-9f5e-xxxx'}}}
最初,我在任何组织目录(任何 Microsoft Entra ID 租户 - 多租户)和个人 Microsoft 帐户(例如 Skype、Xbox)中注册了帐户”Microsoft Entra ID 应用程序:
上传文件时出错:400,{"error":{"code":"BadRequest","message":"/me 请求仅在委托身份验证流程中有效。
当我使用
/me
端点运行您提供的 python 代码时,我遇到了同样的错误。
注意:要将文件上传到 OneDrive-Personal,必须使用涉及用户交互的委托流程,并且必须仅使用
/me
端点;因为应用程序类型 API 权限和客户端凭证流(非用户交互)是不可能的。
要解决该错误,请在涉及用户交互的地方使用委托类型、授权代码流。
添加了委托类型
Files.ReadWrite.All
API 权限和授予管理员同意,如下所示:
应用程序的配置身份验证选项卡如下所示:
使用下面修改后的Python脚本以及使用授权代码流程的委托流程:
import requests
from msal import PublicClientApplication
import os
import time
CLIENT_ID = '<client-id>';
CLIENT_SECRET = '<client-secret>';
file_name= "<file-name to whom you want to upload>";
file_path = "<file-path>";
authority_url = 'https://login.microsoftonline.com/common'
scopes = ['Files.ReadWrite.All']
onedrive_folder ="Documents";
app = PublicClientApplication(CLIENT_ID, authority=authority_url)
# Simplistic approach to illustrate the flow
redirect_uri = 'http://localhost:8000/callback'
url = app.get_authorization_request_url(scopes, redirect_uri=redirect_uri)
print("Please go to this URL and sign-in:", url)
# After sign-in, receive a callback with a code
code = input("Enter the code you received: ")
result = app.acquire_token_by_authorization_code(code, scopes=scopes, redirect_uri=redirect_uri)
if 'access_token' in result:
access_token = result['access_token']
print("Access token acquired.")
else:
print(result.get('error'))
print(result.get('error_description'))
exit(1)
upload_url = f'https://graph.microsoft.com/v1.0/me/drive/root:/{onedrive_folder}/{file_name}:/content'
# Open the file in binary mode
with open(file_path, 'rb') as file:
file_content = file.read()
# Make the PUT request to upload the file
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/octet-stream'
}
response = requests.put(upload_url, headers=headers, data=file_content)
# Check if the file upload was successful
if response.status_code == 201:
print(f'File uploaded successfully to OneDrive: {onedrive_folder}:/{file_name}')
else:
print(f'Error uploading file: {response.status_code}, {response.text}')
从浏览器复制授权码并粘贴到
Enter the code you received:
回复:
我也从 OneDrive Portal 验证了同样的情况,文件
TestUploadOnedrive.xlsx
已成功上传。
上传文件时出错:{'error': {'code': 'BadRequest', 'message': '租户没有 SPO 许可证。', '
要解决此错误,用户应具有有效的 Office 365 E3 许可证或 Office 365 E5 许可证。 请参阅 Rukmini 的 SO 主题。
如果问题仍然存在,请检查此Microsoft QnA,作者:Carl-Zhao-MSFT
参考:
请参阅此 SO 线程,了解租户没有 SPO 许可证。 作者:Dan Kershaw - MSFT。