I have a Python script that will upload a file to Sharepoint using Microsoft Graph but it gives me a 500
status code error when I try to upload the same file twice.
Here is the code for the function that uploads the file:
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
Here is the output for the first run:
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
Here is the output for the second run:
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.'}}
I guess I could figure out how to delete the file before I overwrite it but it would be nice to preserve history since Sharepoint keeps versions.
Thanks for any help on this.
Bobby
p.s. I have been hacking the code in https://github.com/microsoftgraph/python-sample-console-app to get it to upload a file to SharePoint so some of the code in the function is from Microsoft's sample application.