Sharepoint Report Delivery

The code below delivers reports to a Sharepoint server

Note that you need to…

  • Created a new application in your Azure/Entra infrastructure,
  • Created a Token that has a scope that allows writing to Sharepoint with the Graph API,
  • Given the application access to the site in Sharepoint,
  • Installed the office365 package in Python on the ReportList server.

Settings

You'll need several settings to use this script…

SettingDescription
sptennantThe tennant ID for your Office365/Sharepoint subscription
spclientidThe client-ID of your application
spthumbprintThe thumbprint/token for your application
spkeyThe path to your private security key
spurlThe base URL of your Sharepoint installation
spsiteThe path to your Sharepoint site (ie. Sites/Reports)
spfolderThe base folder for your reports (ie. Shared Documents/Reports/Daily)
import time
import sys
import requests
import datetime
import os
import json
import traceback
from office365.sharepoint.client_context import ClientContext
 
f = open(sys.argv[1])
content = f.read()
f.close()
 
details = json.loads(content)
 
#Settings 
tennant = details['options']['sptennant']
clientid = details['options']['spclient']
thumbprint = details['options']['spthumb']
key = details['options']['spkey']
 
baseurl = details['options']['spurl']
basesite = details['options']['spsite']
basefolder = details['options']['spfolder']
 
siteurl = baseurl + basesite
 
#Gather the files to send
fileset = {}
for n in details['files']:
    fileset[n[1]] = n[0]
 
failures = None
 
#If there are any files, send 'em.
if len(fileset) > 0:
 
    for d in details['destinations']:        
 
        ctx = ClientContext.from_url(siteurl).with_client_certificate(tennant, clientid, thumbprint, key)
 
        dir = basefolder + "/" + d['name']        
 
        for f in d['attachments']:
            pth = f[0]
            with open(pth, 'rb') as content_file:
                file_content = content_file.read()
 
            sdir,sname = os.path.split(pth)    
            folder = None
            try:
                folder = ctx.web.get_folder_by_server_relative_url(dir).execute_query()
            except:
                traceback.print_exc()
                if failures is None:
                    failures = "Failed to Find Folder " + dir
                else:
                    failures += " / Failed to Find Folder " + dir
 
            if folder is not None:
                try:
                    file = folder.upload_file(sname, file_content).execute_query()        
                except:
                    if failures is None:
                        failures = "Failed to Upload File " + sname
                    else:
                        failures += " / Failed to Upload File " + sname
                    traceback.print_exc()
 
if failures is None:
    print('----')
    print('SUCCESS')
else:
    print('----')
    print('FAILURE: ' + failures)