我想使用 Microsoft Graph API 更新 Excel 单元格值(托管在 SharePoint 中)。文档在此处。
我已经使用类似于下面的格式成功进行了其他 API 调用(格式更新、清除单元格),请帮助我理解我做错了什么。
在代码示例中,我想将“41373”写入工作表“Plant_3”中的单元格 B:17。代码示例返回400
代码错误:
"code": "InvalidAuthenticationToken",
"message": "Access token is empty.",
此消息可能很笼统,表示 API 调用的格式错误,而不是身份验证问题。其他 Graph API 调用也使用相同的格式id
,keys
因此我怀疑这不是身份验证问题。
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
为data
。 json
在和 中,“41373” 周围都有单括号 / 无括号data
。- 已验证权限,已删除
Files.ReadWrite.All
并出现403
错误。 - 切换“补丁”
post
并尝试上述所有配置。 - 添加
valueType
参数:[['String']]