首页 > 解决方案 > Python:“GetContextWebInformation”更新 SharePoint 列表项

问题描述

我正在尝试通过 python 读取/写入 SharePoint 列表项

我在下面写了成功读取 SharePoint 详细信息作为响应

import requests
from requests_ntlm import HttpNtlmAuth
requests.packages.urllib3.disable_warnings() # suprress all SSL warnings
url = "https://sharepoint.company.com/_api/web/lists/getbytitle('listname')/items?$top=3&$select=ID,Title,Notes" # just reading 3 columns
headers = {'accept': 'application/xml;q=0.9, */*;q=0.8'}
response = requests.get(url, headers=headers, auth=HttpNtlmAuth('domain\\username','Password'), verify=False, stream=True)

现在,当我尝试更新其中一项时,我收到response 403错误

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'}
json_data = [{ '__metadata': { 'type': 'SP.List' }, 'Notes': 'Test Note' }]
response = requests.post(url, { '__metadata': { 'type': 'SP.List' }, 'Notes': 'Test Note' }, headers = self.headers, auth=HttpNtlmAuth('domain\\username','Password'), verify=False)

Microsoft SharePointX-RequestDigest: form digest value必须在标头中发送。

通读文章后,发现以下代码得到form digest value

site_url = "https://sharepoint.company.com"
login_user = 'domain\\username'
auth = HttpNtlmAuth(login_user, 'PASSWORD')
sharepoint_contextinfo_url = self.site_url + '/_api/contextinfo'
headers = {
        'accept': 'application/json;odata=verbose',
        'content-type': 'application/json;odata=verbose',
        'odata': 'verbose',
        'X-RequestForceAuthentication': 'true'
    }
r = requests.post(sharepoint_contextinfo_url, auth=auth, headers=headers, verify=False)
form_digest_value = self.r.json()['d']['GetContextWebInformation']['FormDigestValue']

但是,我没有收到form_digest_value

我试图context info通过浏览器访问https://sharepoint.company.com/_api/contextinfo并收到以下错误:

<?xml version="1.0" encoding="UTF-8"?>
-<m:error xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
    <m:code>-1, Microsoft.SharePoint.Client.ClientServiceException</m:code>
    <m:message xml:lang="en-US">The HTTP method 'GET' cannot be used to access the resource 'GetContextWebInformation'. The operation type of the resource is specified as 'Default'. Please use correct HTTP method to invoke the resource.</m:message>
</m:error>

有人可以帮助如何获得表格摘要值吗?或者是否有更新 SharePoint 列表项?

提前致谢!

更新

看完这篇文章,我明白我们可以从中获取 __REQUESTDIGEST 值Page source。每分钟刷新一次页面,可以看到值不同。如何通过 python 获取请求摘要值并使其保持活动至少 5 分钟?

标签: pythonpython-3.xsharepointpython-requests

解决方案


发布答案,可能对某人有帮助

此处为更新传递的数据未正确完成

所以,通过如下:

json_data = {
    "__metadata": { "type": "SP.Data.TasksListItem" },
    "Title": "updated title from Python"
}

并传递json_data给如下请求:

r= requests.post(api_page, json.dumps(json_data), auth=auth, headers=update_headers, verify=False).text    

上述更改后,代码更新了TitleSharePoint。


推荐阅读