Ways to access/upload documents to SharePoint sites/Document Library using Python script

nagarna1 1 Reputation point
2020-10-28T02:16:27.98+00:00

Hello,

I am new to SharePoint, and trying to upload documents to SharePoint document library. Could you please suggest on how to handle uploading documents to SharePoint using Python.

So far, signed up for 1 month trail SharePoint account and had setup few sites. I am trying this on my Windows 10 laptop.

Getting "permission denied" error while running below Python script.

SP-upload_test.py

============

import requests

from requests_ntlm import HttpNtlmAuth

fileName = 'C:\\Users\\xxxx\\Documents\\Vissu.pdf'
#Enter your SharePoint site and target library

sharePointUrl = 'https://xxxx.sharepoint.com'

folderUrl = '/sites/MyTeam/Internal'

#Sets up the url for requesting a file upload

requestUrl = sharePointUrl + '/_api/web/getfolderbyserverrelativeurl(\'' + folderUrl + '\')/Files/add(url=\'' + fileName + '\',overwrite=true)'
#Read in the file that we are going to upload

file = open(fileName, 'rb')

#Setup the required headers for communicating with SharePoint 

headers = {'Content-Type': 'application/json; odata=verbose', 'accept': 'application/json;odata=verbose'}

#Execute a request to get the FormDigestValue. This will be used to authenticate our upload request

r = requests.post(sharePointUrl + "/_api/contextinfo",auth=HttpNtlmAuth('domain\\user','password'), headers=headers)

print(r.json())

formDigestValue = r.json()['d']['GetContextWebInformation']['FormDigestValue']

#Update headers to use the newly acquired FormDigestValue

headers = {'Content-Type': 'application/json; odata=verbose', 'accept': 'application/json;odata=verbose', 'x-requestdigest' : formDigestValue}

#Execute the request. If you run into issues, inspect the contents of uploadResult

uploadResult = requests.post(requestUrl,auth=HttpNtlmAuth('domain//user','password'), headers=headers, data=file.read())

==================================================================================

print(r.json()) prints below info

{'error': {'code': '-2147024891, System.UnauthorizedAccessException', 'message': {'lang': 'en-US', 'value': 'Access denied. You do not have permission to perform this action or access this resource.'}}}

Receiving "Access denied" for both private and public member, part of privacy settings for the site.
Let me know for any other information. Thanks in advance!

SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
9,617 questions
SharePoint Server Development
SharePoint Server Development
SharePoint Server: A family of Microsoft on-premises document management and storage systems.Development: The process of researching, productizing, and refining new or existing technologies.
1,573 questions
{count} votes

4 answers

Sort by: Most helpful
  1. Jerryzy 10,566 Reputation points
    2020-10-28T07:32:34.393+00:00

    Hi @nagarna1 ,

    If you are using SharePoint Online, please use SharePlum library to upload file into library:

    from shareplum import Office365  
    from shareplum import Site  
    from shareplum.site import Version  
      
    authcookie = Office365('https://TenantName.sharepoint.com', username='userName@TenantName.onmicrosoft.com', password='******').GetCookies()  
    site = Site('https://TenantName.sharepoint.com/sites/SiteName/', version=Version.v365, authcookie=authcookie);  
    folder = site.Folder('Shared Documents')  
    with open("D:\myfile.txt", mode='rb') as file:  
            fileContent = file.read()  
    folder.upload_file(fileContent, "myfile.txt")  
    

    35608-snipaste-2020-10-28-15-16-58.png

    Reference:

    SharePlum Tutorial


    If an Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    3 people found this answer helpful.

  2. Jerryzy 10,566 Reputation points
    2020-10-29T03:11:24.097+00:00

    Hi @nagarna1 ,

    For SharePoint Online, please check if the user account which enabled MFA, then it's not supported, try to close MFA, you can check the detailed Conditional Access Policy as official document:

    Troubleshooting sign-in problems with Conditional Access

    For SharePoint On-Premise(tested in SharePoint 2016 On-Premise), please modify like this:

    from shareplum import Site
    from requests_ntlm import HttpNtlmAuth
    from shareplum.site import Version

    cred = HttpNtlmAuth('Contoso2016\Administrator', 'P@ssw0rd')
    site = Site('http://sp2016/sites/dev', Version.v2016, auth=cred)
    folder= site.Folder('Shared Documents')
    with open("c:\Test.txt",mode='rb') as file:
    fileContent=file.read()
    folder.upload_file(fileContent,"myfile.txt")

    Necessary to specify Version in Site Object, default value is 2007 which has no folder property.

    1 person found this answer helpful.
    0 comments No comments

  3. nagarna1 1 Reputation point
    2020-10-28T13:14:54.673+00:00

    @Jerryzy-MSFT ,

    Thank you for quick response. Receiving below exception when fetching cookies.

    raise Exception('Error authenticating against Office 365. Error from Office 365:', message[0].text)
    Exception: ('Error authenticating against Office 365. Error from Office 365:', 'AADSTS53003: Access has been blocked by Conditional Access policies. The access policy does not allow token issuance.')

    Also, below error when tried On Premise Authentication

    option 1: site = Site('https://<tenant>.sharepoint.com/sites/MyTeam/', auth=cred)

    raise ShareplumRequestError("Shareplum HTTP Post Failed", err)
    shareplum.errors.ShareplumRequestError: Shareplum HTTP Post Failed : 403 Client Error: Forbidden for url: https://tenant.sharepoint.com/sites/MyTeam//\_vti_bin/lists.asmx

    option 2: site = Site('http://<tenant>.sharepoint.com/sites/MyTeam/', auth=cred)

    Traceback (most recent call last):
    File "<pyshell#8>", line 1, in <module>
    site = Site('http://<tenant>.sharepoint.com/sites/MyTeam/', auth=cred)
    File "C:\Users\navee\AppData\Local\Programs\Python\Python38-32\lib\site-packages\shareplum\site.py", line 520, in Site
    return _Site2007(site_url,
    File "C:\Users\navee\AppData\Local\Programs\Python\Python38-32\lib\site-packages\shareplum\site.py", line 95, in init
    self.site_info = self.get_site()
    File "C:\Users\navee\AppData\Local\Programs\Python\Python38-32\lib\site-packages\shareplum\site.py", line 237, in get_site
    data = envelope[0][0][0]
    File "src\lxml\etree.pyx", line 1161, in lxml.etree._Element.getitem
    IndexError: list index out of range

    0 comments No comments

  4. Maulesh Patel 1 Reputation point
    2022-09-27T04:50:58.04+00:00

    Hi Jerryzy,

    This information is quite useful.

    Appreciate the details shared by you.