Python:“ GetContextWebInformation”以更新SharePoint列表项

时间:2019-02-11 14:21:06

标签: python python-3.x sharepoint python-requests

我正在尝试通过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列表项的地方?

谢谢!

已更新

经过this article之后,我了解到我们可以从Page source获得__REQUESTDIGEST值。每分钟刷新页面一次,可以看到值有所不同。如何通过python获取请求摘要值并将其保持至少5分钟的生命?

1 个答案:

答案 0 :(得分:0)

发布答案,也许可以帮助某人

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

因此,如下所示通过了

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    

上述更改之后,代码在SharePoint上更新了Title