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

非交互方式使用Python上传文件到个人OneDrive的报错解决求助

非交互方式使用Python上传文件到个人OneDrive的报错解决求助

我之前试过一些旧的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}')

运行这段代码后,我遇到了下面的错误:

Error uploading file: 400,
{"error":{"code":"BadRequest","message":"/me request is only valid
with delegated authentication
flow.","innerError":{"date":"2025-01-13T17:06:35","request-id":"5959d049-9ad7-4ced-b6fc-00ddddd242","client-request-id":"5959d049-9ad7-4ced-b6fc-0079ddddd"}}}

之后我做了这些调整:

  • 重新创建了应用注册,支持“任何组织目录中的账户(任何Microsoft Entra ID租户 - 多租户)和个人Microsoft账户(如Skype、Xbox)”
  • 给应用添加了这些API权限:
    • Files.ReadWrite.All(应用权限)
    • Sites.ReadWrite.All(应用权限)
    • User.Read.All(应用权限)

然后更新了代码:

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 uploading file: {'error': {'code': 'BadRequest', 'message':
'Tenant does not have a SPO license.', 'innerError': {'date':
'2025-01-14T02:15:47', 'request-id': 'cf70193e-1723-44db-9f5e-xxxxx',
'client-request-id': 'cf70193e-1723-44db-9f5e-xxxx'}}}

请问我该怎么解决这些问题?有没有其他可以非交互上传文件到个人OneDrive的方法?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 13:24:50