0

I am using this much-shared code to try and upload a file to Sharepoint using Shareplum, into the Shared Documents folder.

import requests
from shareplum import Office365

# Set Login Info
username = 'my.email@address.com'
password = 'myverifiedapppassword'
site_name = 'mysite'
base_path = 'https://xxxxxxxx.sharepoint.com'
doc_library = 'Shared%20Documents'
file_name = "hellotest.txt" #when your file in the same directory

# Obtain auth cookie
authcookie = Office365(base_path, username=username, password=password).GetCookies()
session = requests.Session()
session.cookies = authcookie
session.headers.update({'user-agent': 'python_bite/v1'})
session.headers.update({'accept': 'application/json;odata=verbose'})

session.headers.update({'X-RequestDigest': 'FormDigestValue'})
response = session.post(url=base_path + "/sites/" + site_name + "/_api/web/GetFolderByServerRelativeUrl('" + doc_library + "')/Files/add(url='a.txt',overwrite=true)",
                         data="")
session.headers.update({'X-RequestDigest': response.headers['X-RequestDigest']})

# Upload file
with open(file_name, 'rb') as file_input:
    try:
        response = session.post(
            url=base_path + "/sites/" + site_name + f"/_api/web/GetFolderByServerRelativeUrl('" + doc_library + "')/Files/add(url='"
            + file_name + "',overwrite=true)",

            data=file_input)
        print("response: ", response.status_code) #it returns 200
        if response.status_code == '200':
            print("File uploaded successfully")
    except Exception as err:
        print("Something went wrong: " + str(err))

print('File Uploaded Successfully')

The problem is occuring wheen running the code....i am always getting a traceback and a keyerror as follows:

Traceback (most recent call last): File "S:\upload.py", line 22, in session.headers.update({'X-RequestDigest': response.headers['X-RequestDigest']}) File "C:\Python39\lib\site-packages\requests\structures.py", line 54, in getitem return self._store[key.lower()][1] KeyError: 'x-requestdigest'

Something to do with x-requestdigest isnt working properly, in line 22, but i cannot figure out what. Any tips would be greatly appreciated!!!

thanks

yekootmada
  • 21
  • 3
  • 8

1 Answers1

0

I have tried the below code and it is working.

from shareplum import Office365
from shareplum import Site
from shareplum.site import Version

#Logging info
server_url = "https://example.sharepoint.com/"
site_url = server_url + "sites/my_site_name"
Username = 'myusername'
Password = 'mypassword'
Sharepoint_folder = 'Shared Documents'
fileName = 'myfilename'

def file_upload_to_sharepoint(**context):
    authcookie = Office365(server_url, username = Username, password=Password).GetCookies()
    site = Site(site_url, version=Version.v365, authcookie=authcookie)
    folder = site.Folder(Sharepoint_folder)
    with open(fileName, mode='rb') as file:
        fileContent = file.read()
    folder.upload_file(fileContent, "filename.bin")

file_upload_to_sharepoint()

Let me know if this works for you as well.

Rajalakshmi
  • 541
  • 5
  • 21
  • Hi Rajakshmi. thanks for the alternative code. I’m getting an error 403 returned, which I assume is authentication related. ‘ Traceback (most recent call last): File "C:\Python39\lib\site-packages\shareplum\request_helper.py", line 17, in post response.raise_for_status() File "C:\Python39\lib\site-packages\requests\models.py", line 953, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://.sharepoint.com/sites//_vti_bin/‘ – yekootmada Aug 30 '21 at 10:27
  • Hi, please check if your username is added to the Sharepoint site. If not added you cannot have access to the site. – Rajalakshmi Aug 31 '21 at 13:14