I’m trying to use the MS_graph python module to download files from onedrive.
I tried using the pip install msal command. But when you run the code, this error returns:
Traceback (most recent call last):
File "C:/Users/spado/Desktop/ad.py", line 3, in
from ms_graph import generate_access_token, GRAPH_API_ENDPOINT
ModuleNotFoundError: No module named ‘ms_graph‘
I accept any suggestions, even to use other code.
**The code i used:
**
import os
import requests
from ms_graph import generate_access_token, GRAPH_API_ENDPOINT
APP_ID = '<App ID>'
SCOPES = ['Files.Read']
save_location = os.getcwd()
file_ids = ['Folder Id1', 'Folder Id2']
access_token = generate_access_token(APP_ID, scopes=SCOPES)
headers = {
'Authorization': 'Bearer ' + access_token['access_token']
}
# Step 1. get the file name
for file_id in file_ids:
response_file_info = requests.get(
GRAPH_API_ENDPOINT + f'/me/drive/items/{file_id}',
headers=headers,
params={'select': 'name'}
)
file_name = response_file_info.json().get('name')
# Step 2. downloading OneDrive file
response_file_content = requests.get(GRAPH_API_ENDPOINT + f'/me/drive/items/{file_id}/content', headers=headers)
with open(os.path.join(save_location, file_name), 'wb') as _f:
_f.write(response_file_content.content)
2
Answers
Have you installed the python package into your environment?
python3 -m pip install msgraph-core
https://learn.microsoft.com/en-us/graph/tutorials/python?tabs=aad&tutorial-step=2
This is because there is no module named
ms_graph
orgenerate_access_token, GRAPH_API_ENDPOINT
libraries. You need to installmsgraph.core
. The following image indicates the classes present in this librarymsgraph.core
after importing it.However, I see you are trying to retrieve access token. So, one way to achieve this requirement is to use
msal
. Below is the complete code that was working for me.Results: