使用python-sharepoint/shareplum库连接到sharepoint时获取403/401响应代码

2024-06-02 05:23:17 发布

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

我对Python非常陌生,正在尝试将文件上载到SharePoint。 链接格式https://mycompany.sharepoint.com/Shared%20Documents/Forms/ALLItems.aspx。 我正在使用requests_ntlm包、电子邮件和密码进行身份验证,但是当我使用requests.post发布文件时,我得到的是403/401响应代码。 你能就这个问题提出建议吗? 我需要更改SharePoint上的任何设置吗? 此外,请建议是否有任何其他方式上传文件到SharePoint以外的文本文件。你知道吗

代码段:

import requests
import pprint
from requests_ntlm import HttpNtlmAuth
sp_user = 'user@mycompany.onmicrosoft.com'
pwd = 'password'
sp_url = 'https://mycompany.sharepoint.com'
sp_contextinfo_url = 
'https://mycompany.sharepoint.com/sites/testproject/_api/contextinfo'
folderUrl = '/sites/testproject/Shared%20Documents'
headers = {
"Accept":"file/mp4; odata=verbose",
"Content-Type":"file/mp4; odata=verbose",
"odata":"verbose",
"X-RequestForceAuthentication": "true"
}
auth = HttpNtlmAuth(sp_user, pwd)
file1 = 'filename.mp4'
file = open(r'C:\path\to\file\filename.mp4','rb')
requestUrl = sp_url + '/_api/web/getfolderbyserverrelativeurl(\'' + 
folderUrl + '\')/Files/add(url=\'' + file1 + '\',overwrite=true)'
r = requests.post(requestUrl+"/_api/contextinfo",headers=headers,auth =auth)
print(r)

输出:

<Response [401]>

Tags: 文件httpsimportcomapiurlrequestssp