There are several tools out there for interacting with SharePoint through a Python script, but today, I am going to demonstrate a very simple way to upload a file to your SharePoint environment with minimal overhead. This can be useful for users running on Linux environments, such as a Raspberry PI, who want to script some functionality.
Using Octoprint to Monitor 3D Printing
I recently set up a tool called Octoprint on a Raspberry Pi, and am using it to control and monitor the 3D printer here at DMC.
The tool generates timelapses after each print, and it started to take up a lot of space on the Pi’s storage.
I used the following script to take newly rendered timelapses and upload them to SharePoint. This allows users to easily access their print timelapses and frees space on the pi.
Setup
You will need to install the requests package and NTLM authentication package on your environment. In a Linux environment, type the following commands:
1 2 3 | pip install requests
pip install requests_ntlm
|
Python Script
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | import sys
import requests
from requests_ntlm import HttpNtlmAuth
fileName = sys.argv[ 1 ]
folderUrl = '/Your/SharePoint/DocumentLibrary'
requestUrl = sharePointUrl + '/_api/web/getfolderbyserverrelativeurl(\'' + folderUrl + '\')/Files/add(url=\'' + fileName + '\',overwrite=true)'
file = open (fileName, 'rb' )
headers = { 'Content-Type' : 'application/json; odata=verbose' , 'accept' : 'application/json;odata=verbose' }
r = requests.post(sharePointUrl + "/_api/contextinfo" ,auth = HttpNtlmAuth( 'Domain\\username' , 'password' ), headers = headers)
formDigestValue = r.json()[ 'd' ][ 'GetContextWebInformation' ][ 'FormDigestValue' ]
headers = { 'Content-Type' : 'application/json; odata=verbose' , 'accept' : 'application/json;odata=verbose' , 'x-requestdigest' : formDigestValue}
uploadResult = requests.post(requestUrl,auth = HttpNtlmAuth( 'Domain\\username' , 'password' ), headers = headers, data = file .read())
|
Browse to your SharePoint site, and you should now see the newly uploaded file.
Learn more about DMC's SharePoint Consulting Services and Digital Workplace Solutions team. Contact us for your next custom SharePoint project.