Epidemiology & Technology

ODK Central get list of all projects and total submissions

from pprint import pprint
import requests
from requests.exceptions import HTTPError


BASEURL = 'https://ssss.domain.com/v1/'
EMAIL = "drvivek@gmail.com"
PASSWORD = "MYPASSWORD"

# GET TOKEN
try:
    response = requests.post(BASEURL + '/sessions', json={
            "email": EMAIL,
            "password": PASSWORD
    })
    response.raise_for_status()
    jsonResponse = response.json()
    TOKEN = jsonResponse["token"]
   #  print(TOKEN)
    headers = {
        'Authorization': 'Bearer ' + TOKEN,
    }
except HTTPError as http_err:
    print(f'HTTP error occurred: {http_err}')
except Exception as err:
    print(f'Other error occurred: {err}')

headers = {
    'Authorization': 'Bearer ' + TOKEN,
}

xheaders = {
    'Authorization': 'Bearer ' + TOKEN,
    'X-Extended-Metadata': 'true',
}

print (f'{xheaders}')
total_submission = 0
try:
    r_projects = requests.get(BASEURL + 'projects', headers=headers)
    json_projects = r_projects.json()
    #print(f'{json_projects}')
    PROJECTS = len(json_projects)
    print(f'\nTOTAL PROJECTS:  {PROJECTS}')
    for i in range(PROJECTS):
        #print(f'{json_projects[i]}')
        PROJECT = json_projects[i]
        project_id = str(PROJECT['id'])
        print(f"\nID = {project_id}")
        print(f"NAME = {PROJECT['name']}")
        print(f"Archived = {PROJECT['archived']}")
        project_submissions = 0
        try:
            r_forms = requests.get(BASEURL + 'projects/' + project_id + '/forms', headers=xheaders)
            json_forms = r_forms.json()
            FORMS = len(json_forms)

            print(f'TOTAL FORMS: {FORMS}')
            for j in range(FORMS):
                #print(f'{json_forms[j]}')
                form = json_forms[j]
                form_id = str(form['xmlFormId'])
                SUBMISSIONS = form['submissions']
                project_submissions = project_submissions + SUBMISSIONS
                total_submission = total_submission + SUBMISSIONS
                print(f"  SUBMISSIONS: {form['submissions']}  NAME: {form['name']}  STATE: {form['state']} ")

        except HTTPError as http_err:
            print(f'HTTP error occurred: {http_err}')

        finally:
            print(f"PROJECT SUBMISSION:  {project_submissions}")


except HTTPError as http_err:
    print(f'HTTP error occurred: {http_err}')
except Exception as err:
    print(f'Other error occurred: {err}')

finally:
    print(f"\n \nTOTAL SUBMISSIONS: {total_submission}")
Code language: Python (python)

Related Posts