question

nagarna1-7825 avatar image
0 Votes"
nagarna1-7825 asked ·

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

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!

office-sharepoint-onlineoffice-sharepoint-server-development
· 3
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi @nagarna1-7825 ,
Is there any updates ? Did the SharePlum solution work for you ?
If the solution is working, I suggest you could accept as answer so that it could help others in the forum :)

0 Votes 0 ·

No, it has not. Tried all the options but not helpful. Figuring out Conditional Access for SharePoint, as the link that was shared was mostly on Azure (Troubleshooting sign-in problems with Conditional Access).

Is it possible for a screen share session. If not, please let me know any other alternate options. Thanks!

0 Votes 0 ·

Hi @nagarna1-7825,

If need a remote session assistance, I suggest you can submit a Support Request in SharePoint Online Admin Center for furthur troubleshooting:

Ways to contact support for business products - Admin Help


0 Votes 0 ·
Jerryzy-MSFT avatar image
2 Votes"
Jerryzy-MSFT answered ·

Hi @nagarna1-7825,

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.


· 1 ·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi @Jerryzy-MSFT !

That does not work for me.
When I try:

site = Site('https://TenantName.sharepoint.com/sites/SiteName/', version=Version.v365, authcookie=authcookie)

I get the following error:

'RequestsCookieJar' object is not callable


Any suggestions on this?

Many thanks in advance :)

0 Votes 0 ·
nagarna1-7825 avatar image
0 Votes"
nagarna1-7825 answered ·

@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

·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Jerryzy-MSFT avatar image
1 Vote"
Jerryzy-MSFT answered ·

Hi @nagarna1-7825 ,

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.

·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.