如何通过Python中的REST API访问sharepoint站点?

2024-09-28 03:21:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我在本地虚拟机中的SharePoint 2013中有以下网站:

http://win-5a8pp4v402g/sharepoint_test/site_1/

当我从浏览器访问它时,它会提示我输入用户名和密码,然后工作正常。不过,我也在尝试使用Python中的REST API来做同样的事情。我正在使用请求库,这就是我所做的:

import requests
from requests.auth import HTTPBasicAuth


USERNAME = "Administrator"

PASSWORD = "password"

response = requests.get("http://win-5a8pp4v402g/sharepoint_test/site_1/", auth=HTTPBasicAuth(USERNAME, PASSWORD))

print response.status_code

但是我得到了401。我不明白。我错过了什么?

注意:我关注了这篇文章http://tech.bool.se/using-python-to-request-data-from-sharepoint-via-rest/


Tags: fromtestimportauthhttp网站responseusername
3条回答

您的SharePoint站点可能使用不同的身份验证方案。您可以通过检查Firebug或Chrome开发工具中的网络流量来检查这一点。

幸运的是,请求库支持许多身份验证选项:http://docs.python-requests.org/en/latest/user/authentication/

例如,我需要访问的一个网络使用NTLM身份验证。在安装requests-ntml插件之后,我可以使用类似于以下代码访问该站点:

import requests
from requests_ntlm import HttpNtlmAuth

requests.get("http://sharepoint-site.com", auth=HttpNtlmAuth('DOMAIN\\USERNAME','PASSWORD'))

下面是从Python调用SharePoint 2016 REST API创建站点的示例。

import requests,json,urllib
from requests_ntlm import HttpNtlmAuth

root_url = "https://sharepoint.mycompany.com"
headers = {'accept': "application/json;odata=verbose","content-type": "application/json;odata=verbose"}
##"DOMAIN\username",password 
auth = HttpNtlmAuth("MYCOMPANY"+"\\"+"UserName",'Password')


def getToken():
    contextinfo_api = root_url+"/_api/contextinfo"
    response = requests.post(contextinfo_api, auth=auth,headers=headers)
    response =  json.loads(response.text)
    digest_value = response['d']['GetContextWebInformation']['FormDigestValue']
    return digest_value

def createSite(title,url,desc):
    create_api = root_url+"/_api/web/webinfos/add"
    payload = {'parameters': {
            '__metadata':  {'type': 'SP.WebInfoCreationInformation' },
            'Url': url,
            'Title': title,
            'Description': desc,
            'Language':1033,
            'WebTemplate':'STS#0',
            'UseUniquePermissions':True}
        }
    response = requests.post(create_api, auth=auth,headers=headers,data=json.dumps(payload))
    return json.loads(response.text)

headers['X-RequestDigest']=getToken()
print createSite("Human Resources","hr","Sample Description")

您还可以使用PyPI中的sharepoint模块,自称为“从SharePoint获取数据的模块和命令行实用程序”

相关问题 更多 >

    热门问题