Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagepy
themeMidnight
titleCreate test and assign candidates using the IA API
linenumberstrue
import requests
import os
import csv
import sys

# this has to be manually replaced by a valid auth token and client id, if env vars not set
auth_token = os.environ['IA_ACCESS_TOKEN']
client_id = os.environ['IA_CLIENT_ID']
# this typically has the form https://<CLIENT>.inspera.no/api/
api_base_url = os.environ['IA_API_URL']
api_auth_path = "authenticate/token/"
auth_params = {"code": auth_token, "client_id": client_id, "grant_type": "authorization_code"}
api_create_test_path = "v1/test"
api_assign_candidates_path = "v1/test/%d/candidates" # %d to be replaced by testId before using the URL, sprintf-style

# this will be the external id of the test created
ext_test_id = "externalTest123456789"

# this will be the name of the test created
test_name = "UNSW API testing test updated";

def get_student_list_from_csv(csv_file_name):
    """Helper to grab a list of students from a local CSV file.
       This could be data coming from your DB/integration platform. """
    students = []
    with open(csv_file_name, 'r') as csvfile:
        csvreader = csv.reader(csvfile, delimiter = ',')
        for s in csvreader:
            student = {}
            student["candidateId"] = s[0]
            student["buildingName"] = s[1]
            student["roomName"] = s[2]
            student["externalId"] = s[3]
            student["extraTimeMinutes"] = s[4]
            students.append(student)
    return students

def create_ia_test(token, test_name, test_id, start_time, end_time):
    """Helper that creates a test in IA with the given (external) id and name,
       using the Inspera API with the given session token."""
    create_test_params = {  "externalTestId": test_id,
                            "title": test_name,
                            "startTime": start_time,
                            "endTime": end_time
                          }
    result = requests.post(api_base_url + api_create_test_path, json=create_test_params,
                           headers={"Authorization": "bearer " + token, "Content-type": "application/json"})
    #print result.text
    return result.json()["assessmentRunId"]

def assign_candidates(token, test_id, candidates):
    """Helper that assignes the given list of candidates to a test in IA given the IA id of the test,
       using the Inspera API with the given session token."""
    assign_candidate_params = {"testId": test_id, "candidates" : candidates}
    assign_candiates_url = api_base_url + (api_assign_candidates_path % test_id)
    result = requests.post(assign_candiates_url, json=assign_candidate_params,
                           headers={"Authorization": "bearer " + token, "Content-type": "application/json"})
    print(result.text)

print("Creating a test in IA and populating some students from CSV...")
if not len(sys.argv) == 2:
    print("Please provide the CSV file name as the only script parameter")
else:	
    session_token = requests.post(api_base_url + api_auth_path, data = auth_params, headers={"code": auth_token}).json()["access_token"]
    print("Will go on using token " + session_token)
    ia_test_id = create_ia_test(session_token, test_name, ext_test_id, "2018-05-25T12:30:00Z", "2018-05-25T17:30:00Z")
    print("Will assign students to test " + str(ia_test_id))
    students = get_student_list_from_csv(sys.argv[1])
    assign_candidates(session_token, ia_test_id, students)
    print("Assigned " + str(len(students)) + " candidates to test " + str(ia_test_id))



...

Code Block
languagepy
themeMidnight
titleCreate some planners using the IA API
linenumberstrue
import requests
import os
import csv
import sys

# this example creates a few test planners from a CSV file given as a parameter to the script

# this has to be manually replaced by a valid auth token and client id, if env vars not set
auth_token = os.environ['IA_ACCESS_TOKEN']
client_id = os.environ['IA_CLIENT_ID']
# this typically has the form https://<CLIENT>.inspera.no/api/
api_base_url = os.environ['IA_API_URL']
api_auth_path = "authenticate/token/"
auth_params = {"code": auth_token, "client_id": client_id, "grant_type": "authorization_code"}
api_create_admin_path = "v1/users/admin/"

def get_planner_list_from_csv(csv_file_name):
    """Helper to grab a list of test planners from a local CSV file.
       This could be data coming from your DB/integration platform. """
    admins = []
    with open(csv_file_name, 'r') as csvfile:
        csvreader = csv.reader(csvfile, delimiter=',')
        for a in csvreader:
            admin = {}
            admin["externalId"] = a[0]
            admin["authType"] = a[1]
            admin["username"] = a[2]
            admin["firstName"] = a[3]
            admin["lastName"] = a[4]
            admin["email"] = a[5]
            admin["orgUnitMemberships"] = a[6]
            admins.append(admin)
    return admins

def create_ia_test_planner(token, planner):
    """Helper that creates a planner in IA with the given values,
       using the Inspera API with the given session token."""
    create_planner_params = planner
    # roles is now an array replacing the old "role"
    planner["roles"] = ["plan"]; # "evaluate", "plan", "author" supported, could also come from ext system, but hardcoded for demo
    result = requests.post(api_base_url + api_create_admin_path, json=create_planner_params,
                           headers={"Authorization": "bearer " + token, "Content-type": "application/json"})

    print(result.text)
    print(result.request.body)
    return result.json()["userId"]


print("Creating test planners in IA from CSV...")
if not len(sys.argv) == 2:
    print("Please provide the CSV file name as the only script parameter")
else:	
    response = requests.post(api_base_url + api_auth_path, data=auth_params, headers={"code": auth_token})
    print(response.text)
    session_token = response.json()["access_token"]
    print("Will go on using token " + session_token)
    planners = get_planner_list_from_csv(sys.argv[1])
    ia_planner_ids = []
    for planner in planners:
        print("Will create planner " + str(planner["firstName"]) + " " + str(planner["lastName"]))
        ia_planner_ids.append(create_ia_test_planner(session_token, planner))
    print("Created " + str(len(planners)) + " in IA, userIds in IA: " + str(ia_planner_ids))




...