1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Python Upload Files to Sharepoint using Shareplum

Discussão em 'Python' iniciado por Stack, Setembro 28, 2024 às 10:13.

  1. Stack

    Stack Membro Participativo

    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

    Continue reading...

Compartilhe esta Página