尝试使用Python和REST API将文件上载到Sharepoint时出错400

尝试使用Python和REST API将文件上载到Sharepoint时出错400,python,rest,api,sharepoint,upload,Python,Rest,Api,Sharepoint,Upload,我正在尝试编写一个python脚本,可以访问sharepoint并将excel文件上载到其中。我已经成功地通过了身份验证并检索了FormDigestValue,但是我似乎无法正确地获取upload命令。以下是我目前的代码: import requests from requests_ntlm import HttpNtlmAuth #get formdigestvalue headers = {'accept': 'application/json;odata=verbose'} r = re

我正在尝试编写一个python脚本,可以访问sharepoint并将excel文件上载到其中。我已经成功地通过了身份验证并检索了FormDigestValue,但是我似乎无法正确地获取upload命令。以下是我目前的代码:

import requests
from requests_ntlm import HttpNtlmAuth

#get formdigestvalue
headers = {'accept': 'application/json;odata=verbose'}
r = requests.post("https://sharepoint.example.com/example/_api/contextinfo",auth=HttpNtlmAuth('username', 'password'), headers=headers)
print r.status_code
FormDigestValue = r.json()['d']['GetContextWebInformation']['FormDigestValue']
print FormDigestValue

#file upload
POSTheaders = {'Accept':'application/json; odata=verbose','Content-Type':'application/json; odata=verbose',
               'X-RequestDigest':FormDigestValue, 'binaryStringRequestBody':'true'}

posturl = "https://sharepoint.example.com/example/_api/web/GetFolderByServerRelativeUrl('Trainings/Training Records/JohnSmith')/files/add(url=""test.xlsx"", overwrite='true')"

excelfile = {'file': ('test.xlsx', open('test.xlsx', 'rb'), 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')}

auth=HttpNtlmAuth('username', 'password')

p = requests.post(posturl, headers=POSTheaders, files = excelfile, auth = auth)

print p.status_code
print p.content
我从中得到的输出如下:

200
0x63B311022FB07B3B7D7751B0B06C2EF0232DDACD9255DF871FD7599E08A2A014B06ED22DE55246C7F0C7459D8717E347631390502ED7556C6019BB69C7745EA0,15 Feb 2017 12:50:17 -0000
400
{"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"The expression \"web/GetFolderByServerRelativeUrl('Trainings/Training Records/JohnSmith')/files/add(url=test.xlsx, overwrite='true')\" is not valid."}}}

不幸的是,错误消息没有给出太多关于错误的细节,无论我如何调整post请求,我都无法通过它。任何关于我做错了什么的想法都将不胜感激。

我想你需要在这里用单引号
url=test.xlsx
。消息说该查询不正确,或者确切地说语法不正确。下面是使用单引号的示例链接。单引号的问题是Python将该部分视为一个变量,而我在尝试运行脚本时出错。有没有一种方法可以使它成为单引号,但不从post请求的大字符串中删除它?Python支持字符转义吗?它必须是这样的
“\”
。这也是您的字符串右侧
“https://sharepoint.example.com/example/_api/web/GetFolderByServerRelativeUrl('Trainings/Training Records/JohnSmith')/files/add(url=”“test.xlsx',overwrite='true')”
我清楚地看到您在任何地方都使用单引号,但在这里
url=”“test.xlsx”“
,为什么不能在这里使用?尝试使用
url='test.xlsx'
或转义单引号
url='test.xlsx\'
就是这样,与url='test.xlsx'配合使用很好。我不知道我怎么没发现这一点;非常感谢你的帮助。