【发布时间】:2018-07-27 17:00:48
【问题描述】:
我有一个 Python 脚本,它可以使用 Microsoft Graph 将文件上传到 Sharepoint,但是当我尝试两次上传同一个文件时,它给了我一个 500 状态代码错误。
上传文件的函数代码如下:
def upload_file(session,filename,driveid,folder):
"""Upload a file to Sharepoint.
"""
fname_only = os.path.basename(filename)
# create the Graph endpoint to be used
endpoint = f'drives/{driveid}/root:/{folder}/{fname_only}:/createUploadSession'
start_response = session.put(api_endpoint(endpoint))
json_response = start_response.json()
upload_url = json_response["uploadUrl"]
# upload in chunks
filesize = os.path.getsize(filename)
with open(filename, 'rb') as fhandle:
start_byte = 0
while True:
file_content = fhandle.read(10*1024*1024)
data_length = len(file_content)
if data_length <= 0:
break
end_byte = start_byte + data_length - 1
crange = "bytes "+str(start_byte)+"-"+str(end_byte)+"/"+str(filesize)
print(crange)
chunk_response = session.put(upload_url,
headers={"Content-Length": str(data_length),"Content-Range": crange},
data=file_content)
if not chunk_response.ok:
print(f'<Response [{chunk_response.status_code}]>')
pprint.pprint(chunk_response.json()) # show error message
break
start_byte = end_byte + 1
return chunk_response
这是第一次运行的输出:
bytes 0-10485759/102815295
bytes 10485760-20971519/102815295
bytes 20971520-31457279/102815295
bytes 31457280-41943039/102815295
bytes 41943040-52428799/102815295
bytes 52428800-62914559/102815295
bytes 62914560-73400319/102815295
bytes 73400320-83886079/102815295
bytes 83886080-94371839/102815295
bytes 94371840-102815294/102815295
这是第二次运行的输出:
bytes 0-10485759/102815295
bytes 10485760-20971519/102815295
bytes 20971520-31457279/102815295
bytes 31457280-41943039/102815295
bytes 41943040-52428799/102815295
bytes 52428800-62914559/102815295
bytes 62914560-73400319/102815295
bytes 73400320-83886079/102815295
bytes 83886080-94371839/102815295
bytes 94371840-102815294/102815295
<Response [500]>
{'error': {'code': 'generalException',
'message': 'An unspecified error has occurred.'}}
我想我可以在覆盖之前弄清楚如何删除文件,但保留历史记录会很好,因为 Sharepoint 会保留版本。
感谢您对此的任何帮助。
鲍比
附言我一直在破解 https://github.com/microsoftgraph/python-sample-console-app 中的代码,让它将文件上传到 SharePoint,因此函数中的一些代码来自 Microsoft 的示例应用程序。
【问题讨论】:
-
我最终在上传之前添加了删除文件的代码,这解决了问题。 github.com/bobbydurrett/copyfiletosharepoint 很高兴知道为什么我在覆盖文件时收到 500 错误。
标签: python sharepoint microsoft-graph-api onedrive