Загрузите файл в 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"}}}

Как устранить эту ошибку? или любой альтернативный способ загрузки файлов

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

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

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

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

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

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Загрузите файл в onedrive Personal с помощью Python в неинтерактивном режиме.
    Anonymous » » в форуме Python
    0 Ответы
    11 Просмотры
    Последнее сообщение Anonymous
  • Передача параметров исполняемому файлу Python в неинтерактивном режиме
    Anonymous » » в форуме Python
    0 Ответы
    24 Просмотры
    Последнее сообщение Anonymous
  • Загрузите большой файл на onedrive с помощью C# и .NET 5.0 [закрыто]
    Anonymous » » в форуме C#
    0 Ответы
    22 Просмотры
    Последнее сообщение Anonymous
  • Загрузите файл в C# Asp.Net Core в Sharepoint/OneDrive с помощью Microsoft Graph без взаимодействия с пользователем.
    Anonymous » » в форуме C#
    0 Ответы
    24 Просмотры
    Последнее сообщение Anonymous
  • Загрузите файл OneDrive с Curl, так как они изменили конструкцию своего URL -адреса
    Anonymous » » в форуме Php
    0 Ответы
    9 Просмотры
    Последнее сообщение Anonymous

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