Home > Enterprise >  Python Script to connect to One Drive for Business
Python Script to connect to One Drive for Business

Time:09-21

I am trying to connect to One drive for Business using this script.

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)

I have registered an application enabled implicit flow in the manifest and given it the Sites.AllRead permission. Upon using this, I was getting asked for 2FA probably because Azure saw it as a risky sign in. Instead of delegated permissions, I gave the app application permissions and enable the "allowPublicClient": true, in the app manifest. My question is, how do I specify which OneDrive I need to connect to? I mean which user's OneDrive ,I am looking to connect to how do I specify that in the code? Do I need to authenticate to that user?

Above code is from here

CodePudding user response:

Microsoft Graph OneDrive Root Resources

You could use the following Graph API requests to interact with specific OneDrive.

  1. /drives - List drive resources available to the authenticated user.
  2. /drives/{drive-id} to Access a specific drive by its ID.
  • Related