Management

Manage Schedules

This example works in unison with our Discovery Database. Once you’ve identified schedules from reports that need to be removed, this script will take the query results and iterate over them to remove all schedules returned from the query.

How this example works

In this example the main method, remove_unnecessary_schedules, will use a few helper methods to find the query results from a query that points at the Mode Discovery Database. This will allow you to programmatically delete schedules that either exceed a certain gb_data_usage, were created by former members, run within a personal space, run at a high frequency or any metric you would like to put in place to manage schedules.

To try it yourself

  • Input the API token, API secret, Workspace name, and other custom information as needed. Follow these steps to create an API token.
  • Save the file in your desired directory
  • Open the terminal and navigate to that directory
  • Run the command python3 {file_name}.py for python or Node/Express to run the JS library
import json
import requests

from requests.auth import HTTPBasicAuth


host = 'https://app.mode.com'
ws = 'workspace_name' # Note: workspace_name value should be all lowercase
un = 'api_token'
pw = 'api_secret'


def remove_unnecessary_schedules(report_token,query_name):
   url = url = '%s/api/%s/reports/%s/queries' % (host, ws, report_token)
   r = requests.get(url, auth=HTTPBasicAuth(un, pw))
   result = r.json()['_embedded']['queries']
   query = ''
   results = ''

   for q in result:
       if q["name"] == query_name:
           query = q
   if query:
       results = get_query_result(report_token,query['token'])
   else:
       return "No Query Found"

   for s in results:
       remove_schedule(s['report_id'] ,s['schedule_token'])


def get_query_result(report_token, query_token):
 url = '%s/api/%s/reports/%s/queries/%s/runs' % (host, ws, report_token, query_token)
 r = requests.get(url, auth=HTTPBasicAuth(un, pw))
 result = r.json()

 if result['_embedded']['query_runs'][0]['state'] == 'succeeded':
   query_run_result_endpoint = result['_embedded']['query_runs'][0]['_links']['result']['href']
   print(query_run_result_endpoint)
   return get_run_result(query_run_result_endpoint)
 else:
   print ('There is no results, because query run failed.')


def get_run_result(query_run_result_endpoint):
 url = '%s%s/content.json' % (host, query_run_result_endpoint)
 r = requests.get(url, auth=HTTPBasicAuth(un, pw))
 result = r.json()
 return result


def remove_schedule(report_token,schedule_token):
 url = '%s/api/%s/reports/%s/schedules/%s' % (host, ws, report_token,schedule_token)
 headers = {'Content-Type': 'application/json'}
 r = requests.delete(url, headers=headers, auth=HTTPBasicAuth(un,pw))
 print ('Schedule Token:%s has been deleted' % (schedule_token) )
remove_unnecessary_schedules('Report_Token','Query_Name')
const request = require('request-promise');

const host = 'https://app.mode.com';
const ws = 'workspace_name'; // Note: workspace_name value should be all lowercase
const username = 'api_token';
const password = 'api_secret';

const removeUnnecessarySchedules = async (reportToken,queryName) => {

   let reportQueries = await request({
     method: 'GET',
     url: `${host}/api/${ws}/reports/${reportToken}/queries`,
     auth: { username, password },
     json: true  });

   let query = reportQueries._embedded.queries.filter(q => q.name === queryName)
   let results;

   if(query[0]){
     results =  await getQueryResult(reportToken,query[0].token)
   } else{
     return "No Query Found"
   }

   results.forEach((r)=>{
      removeSchedule(r.report_id,r.schedule_token)
   })
};

const getQueryResult = async (reportToken,queryToken)=>{
  let queryRuns =  await request({
    method: 'GET',
    url: `${host}/api/${ws}/reports/${reportToken}/queries/${queryToken}/runs`,
    auth: { username, password },
    json: true  });

    if(queryRuns._embedded.query_runs[0].state === "succeeded"){
      let queryRunURL = queryRuns._embedded.query_runs[0]._links.result.href
      return await getRunResults(queryRunURL)
    } else{
      console.log('There is no results, because query run failed.')
    }
};

const getRunResults = async (queryRunURL)=>{
  let results = await request({
    method: 'GET',
    url: `${host}${queryRunURL}/content.json`,
    auth: { username, password },
    gzip: true,
    json: true  });
  return results;
};

const removeSchedule = (reportToken,scheduleToken)=>{
  let schedule = request({
    method: 'DELETE',
    url: `${host}/api/${ws}/reports/${reportToken}/schedules/${scheduleToken}`,
    auth: { username, password },
    json: true  });

    console.log(`Schedule Token:${scheduleToken} has been deleted`)
};

removeUnnecessarySchedules('Report_Token','Query_Name')