Как отформатировать вызов Graph API для обновления ячейки Excel?Python

Программы на Python
Anonymous
Как отформатировать вызов Graph API для обновления ячейки Excel?

Сообщение Anonymous »

Я хочу обновить значение ячейки Excel (размещенной в SharePoint) с помощью API Microsoft Graph. Документация находится здесь.
Мне удавалось успешно выполнять другие вызовы API (обновление формата, очистка ячеек), используя формат, аналогичный приведенному ниже; что я делаю не так?
В примере кода я хочу написать «41373» в ячейку B:17 на листе «Plant_3». Пример кода возвращает ошибку кода 400:

Код: Выделить всё

"code": "InvalidAuthenticationToken",
"message": "Access token is empty.",
Это сообщение может быть общим и означать неправильное форматирование вызова API, а не проблему аутентификации. Другие вызовы API Graph работают с теми же идентификаторами и ключами, поэтому я сомневаюсь, что это проблема аутентификации.

Код: Выделить всё

def graph_config_params():
"""
read authentication parameters from config file, return dict with results
:return: (dict) configuration parameters
"""
try:
# Read the config file
config = configparser.ConfigParser()
config.read('config.ini')
# assign authorization tokens from config file to variables
return_dict = {'client_id': config['entra_auth']['client_id'],
'client_secret': config['entra_auth']['client_secret'],
'tenant_id': config['entra_auth']['tenant_id'],
# Get necessary configuration data for the SharePoint file
'site_id': config['site']['site_id'],
'document_library_id': config['site']['document_library_id'],
'doc_id': config['site']['doc_id'],
'drive_id': config['site']['drive_id']}
return return_dict
except Exception as e:
log.exception(e)
def set_up_ms_graph_authentication(graph_auth_args=graph_config_params()):
"""
Create headers with access token for Microsoft Graph API to authenticate
:param graph_authentication_params:
:return: (dict) headers with access token
"""
try:
# Set up Microsoft Graph authentication
msal_scope = ['https://graph.microsoft.com/.default']
msal_app = ConfidentialClientApplication(
client_id=graph_auth_args['client_id'],
authority=f"https://login.microsoftonline.com/{graph_auth_args['tenant_id']}",
client_credential=graph_auth_args['client_secret'])
result = msal_app.acquire_token_silent(scopes=msal_scope,
account=None)
if not result:
result = msal_app.acquire_token_for_client(scopes=msal_scope)
if 'access_token' in result:
access_token = result['access_token']
else:
raise Exception("Failed to acquire token")
# Prepare request headers with the acquired access token
headers = {'Authorization': f'Bearer {access_token}'}
# log.info(f'headers: {headers}')
return headers
except Exception as e:
log.exception(e)
sheet = 'Plant_3'
# get variables that work in other Graph API calls
config_args=graph_config_params()
# get Authorization Bearer token, again works in other Graph API calls.
my_headers = set_up_ms_graph_authentication()
url=  f"https://graph.microsoft.com/v1.0/sites/{config_args['site_id']}/drives/{config_args['drive_id']}/items/{config_args['doc_id']}/workbook/worksheets/{sheet}/range/(address='B:17')"
response = requests.patch(url,
headers=my_headers,
json={'values': [['41373']] })
Что я пробовал:
  • Переключил аргумент ключевого слова с json на данные.
  • Одиночные скобки / без квадратных скобок вокруг '41373', как в json, так и в данных.
  • Проверил разрешения, удалил Files.ReadWrite.All и получил Ошибка 403.
  • Переключил «исправление» на публикацию и попробовал все конфигурации, упомянутые выше.
  • Добавление аргумента valueType: [['String']]

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