skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. This is because there is no module named ms_graph or generate_access_token, GRAPH_API_ENDPOINT libraries. You need to install msgraph.core. The following image indicates the classes present in this library msgraph.core after importing it.

    enter image description here

    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.

    import webbrowser
    from msal import ConfidentialClientApplication, PublicClientApplication
    
    client_secret = '<YOUR_CLIENT_SECRET>'
    client_id = '<YOUR_CLIENT_ID>'
    
    SCOPES = ['User.Read']
    client = ConfidentialClientApplication(client_id=client, client_credential=client_secret)
    authorization_url = client.get_authorization_request_url(SCOPES,redirect_uri='<YOUR_REDIRECT_URL>') 
    webbrowser.open(authorization_url)
    
    authorization_code = '<AUTHORIZATION_CODE>'
    access_token = client.acquire_token_by_authorization_code (code=authorization_code, scopes=SCOPES,redirect_uri='<YOUR_REDIRECT_URL>')
    access_token_id = access_token['access_token']
    print(access_token_id)
    

    Results:

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search