Загрузите файл в onedrive Personal с помощью Python в неинтерактивном режиме.Python

Программы на Python
Ответить
Anonymous
 Загрузите файл в onedrive Personal с помощью Python в неинтерактивном режиме.

Сообщение Anonymous »

Я видел какой-то старый метод с использованием 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,
{"ошибка": {"code":"BadRequest","message":"/me запрос действителен только
с делегированной аутентификацией
flow.","innerError":{"date":"2025-01-13T17:06:35","request-id":"5959d049-9ad7-4ce d-b6fc-00dddd242","client-request-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', 'идентификатор-запроса': 'cf70193e-1723-44db-9f5e-xxxxx',
'идентификатор-клиента-запроса': 'cf70193e-1723-44db-9f5e-xxxx'}}


Подробнее здесь: https://stackoverflow.com/questions/793 ... active-way
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»