Подключение к SharePoint и чтение файла excel с помощью oauth2 (clientID, client_secret) - Python

Я пытаюсь считать файл excel из SharePoint и сделать dataframe.

У меня есть код, который использует имя пользователя и пароль, но меня попросили изменить мой метод на oauth2.

Старый код, который работал:

from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.client_context import ClientCredential
import io
import pandas as pd
from office365.sharepoint.files.file import File


SP_SITE_URL ='https://companyname.sharepoint.com/sites/sitename' 
    
username= config["sharepoint"]["username"]
password= config["sharepoint"]["password"]

client_credentials = ClientCredential(userID, password)
ctx = ClientContext(SP_SITE_URL).with_user_credentials(userID,password)

file_url = FOLDER_URL + current_file_name
response = File.open_binary(ctx, file_url)

bytes_file_obj = io.BytesIO()
bytes_file_obj.write(response.content)
bytes_file_obj.seek(0) #set file object to start

#read file into pandas dataframe
df = pd.read_excel(bytes_file_obj)

Я попытался переключить учетные данные на ClientID и Clientsecrent:

client_id = config["sharepoint"]["clientID"]
client_secret = config["sharepoint"]["client_secret"]
client_credentials = ClientCredential(client_id, client_secret)
ctx = ClientContext(SP_SITE_URL).with_credentials(client_credentials)

file_url = FOLDER_URL + current_file_name

response = File.open_binary(ctx, file_url)

bytes_file_obj = io.BytesIO()
bytes_file_obj.write(response.content)
bytes_file_obj.seek(0) #set file object to start

df = pd.read_excel(bytes_file_obj)

Но я получаю ошибку:

ClientRequestException: ('-2147024891, System.UnauthorizedAccessException', 'Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))', '403 Client Error: Forbidden for url: https://companyname.sharepoint.com/sites/sitename/_api/Web'

Ответы (1 шт):

Автор решения: Vazhik

Проблему решил, надеюсь поможет кому нибудь) Пробовал на командном sharepoint (на личном не пробовал)

def read_excel_sharpoint(folder, file_name, sheet, site='название командного sharepoint', 
                         main_folder='General/Shared_access/'):
    
    data = {'username': user_azure, 'password': password_azure, 'client_id': client_id, 
            'client_secret': client_secret,'scope': (['Sites.ReadWrite.All']), 'grant_type': 'password'}

    response = requests.get(url=f"https://login.microsoftonline.com/{tennant}/oauth2/v2.0/token", 
                            headers={'Content-Type': 'application/x-www-form-urlencoded'}, data=data)

    if response.status_code == 200:
        access_token = response.json()['access_token']
    else:
        raise Exception("Sharepoint API not authorized!")

    response = requests.get(
        url=f'https://graph.microsoft.com/v1.0/sites?$search="{site}"',
        headers={'Authorization': f'Bearer {access_token}', 
                 'Content-Type': 'application/json',})
    
    site_id = response.json()['value'][0]['id']
    item = f"{main_folder}{folder}/{file_name}"

    response = requests.get(url=f'https://graph.microsoft.com/v1.0/sites/{site_id}/drive/root:/{item}',
                            headers={'Authorization': f'Bearer {access_token}', 
                                     'Content-Type': 'application/json',})
    item_id = response.json()['id']

    response = requests.get(
        url=f'https://graph.microsoft.com/v1.0/sites/{site_id}/drive/items/{item_id}/content', 
        headers={'Authorization': f'Bearer {access_token}',})

    bytes_ = BytesIO()
    bytes_.write(response.content)
    bytes_.seek(0)

    return pd.read_excel(bytes_, sheet_name=sheet, engine='openpyxl')
  • main_folder - основная папка, в которой хранятся папки с нужными файлами
  • folder - папка после main_folder
  • file_name - название файла
  • 1234.xlsx в папке folder sheet - название нужного листа
→ Ссылка