Google Drive Report Delivery
The code below delivers reports to a Google Drive folder.
Note that you need to…
- Have created a Google Cloud application,
- Created a Service Account under that application with a JSON key,
- Enabled the Google Drive API for the application,
- Installed the pydrive2 package in Python on the ReportList server, and
- Copied your JSON key into the Report Directory named googlekey.json.
- Shared the target folder(s) - with at least Edit permissions - with the service account user.
Destination
The destination (specified in your subscription in the reporting addon) should be the unique ID of the destination Google Drive folder.
For example, gdrive#28372dgjs_22831 would upload data to the folder '28372dgjs_22831'. You can find this unique ID in the address bar when you open the Google Drive folder in your browser.
Note that you must share this folder with the service account user in Google Drive to be permitted to write files.
import time import sys import requests import datetime import os import json import traceback import os from pydrive2.auth import GoogleAuth from pydrive2.drive import GoogleDrive from oauth2client.service_account import ServiceAccountCredentials failedfiles = [] failreason = None f = open(sys.argv[1]) content = f.read() f.close() details = json.loads(content) jsonfile=os.path.dirname(__file__) + "/googlekey.json" # Define the Google Drive API scopes and service account file path gauth = GoogleAuth() # NOTE: if you are getting storage quota exceeded error, create a new service account, and give that service account permission to access the folder and replace the google_credentials. gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name(jsonfile, scopes=['https://www.googleapis.com/auth/drive']) drive = GoogleDrive(gauth) print("Setup Connection to Google Drive") # ID of channel that you want to upload file to for d in details['destinations']: folder_id = d['name'] for att in d['attachments']: try: # Uploading files requires the `files:write` scope file1 = drive.CreateFile( {'parents': [{"id": folder_id}], 'title': att[1]}) file1.SetContentFile(att[0]) file1.Upload() except: traceback.print_exc() failedfiles.append(att[1]) if failreason is not None: failreason += " / Could Not Upload" else: failreason = "Could Not Upload" if len(failedfiles) > 0: print("-----") print(failreason) else: print("-----") print("SUCCESS")