-
-
Save unabridgedxcrpt/1418d8b32b9ad7fa418325b00759c114 to your computer and use it in GitHub Desktop.
This is a sample Python program demonstrating how to use the Canvas API to pull a list of active courses with total score information. Produces CSV with Percent & Letter Grade.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests, json | |
from pprint import pprint | |
from urllib.request import Request, urlopen | |
import csv | |
import os | |
import timeit | |
def getInput(file): | |
'''Opens the file, produces list of lines in the file, removes the header row, and returns the list''' | |
inFile = open(file) | |
inputList = inFile.read().splitlines() | |
del inputList[0] | |
inFile.close() | |
return inputList | |
def clean_data(): | |
'''Produces final list for use in rest of program.''' | |
outlist = [] | |
for line in stu_lines: | |
# put the line parts into a list | |
items = line.split(',') | |
#assign variables to each item to be used | |
firstname = items[3] | |
lastname = items[4] | |
user = str(items[0]) | |
grade = str(items[2]) | |
outlist.append([user,firstname,lastname,grade]) | |
return(outlist) | |
################################################################################# | |
# Main Program # | |
################################################################################# | |
#Get data from input CSV file | |
# CSV file in this example is in the following format: | |
# Canvas SIS ID, internal Student ID, Grade Level, LastName, FirstName | |
stu_lines = getInput('C:\\Path\\to\\input_csv_file') | |
stu_list = clean_data() | |
#Enter Canvas APi token to set up API Call | |
token = 'your token here' | |
request_headers={'Authorization': token} | |
#Setup outfile and header | |
outFile = open('C:\\Path\\To\\final_csv_file', 'w') | |
header = ['User ID','Last Name','First Name','Grade','Course Title','Teacher','Percent','Letter Grade'] | |
columnHead = ','.join(header) | |
outFile.write(columnHead + '\n') | |
#Iterate through sudent list and set data to make API call to Canvas | |
count = 0 | |
for i in stu_list: | |
#set data for call to canvas and for export | |
user = i[0] | |
lastname = i[1] | |
firstname = i[2] | |
grade = i[3] | |
#prepare url using info in user and name variables | |
# This url pulls all ACTIVE courses and associated scores | |
url = 'https://guerincatholic.instructure.com/api/v1/users/sis_user_id:'+user+'/courses.json?include[]=total_scores&enrollment_state=active' | |
#info for each api call | |
q = Request(url) | |
q.add_header('Authorization', 'Bearer ' + token) | |
u = urlopen(q) | |
#make the call and retrieve data | |
data = json.loads(u.read().decode()) | |
#set variables for final csv file | |
part1 = [user,lastname,firstname, grade] | |
temp1 =','.join(part1) | |
#iterate through JSON data to: | |
# 1) edit course titles. Our course titles include the term & teacher. | |
# You may not need to edit depenging on your naming convention. | |
# 2) Add edited information to a list used to build final csv | |
for i,val in enumerate(data): | |
#Set up a list for enrollment data | |
enroll_list = [] | |
#Set up variables | |
enrollments = data[i]['enrollments'] | |
course = (data[i]['course_code']) | |
#Skip karios courses & 5th period cadet teaching & internship courses | |
# This is specific to our school. | |
if '.K' in course: continue | |
elif '5th' in course: continue | |
elif 'T3.0-Intermediate Concert Band' in course: continue | |
elif 'T2.0-Intermediate Concert Band' in course: continue | |
#Skip open courses from previous terms. Comment out, as needed. | |
# T1, T2, T3 start each of our course titles.(i.e. T1.2-Course Title-Teacher Last Name) | |
# The following lines ensure that we only get courses for the current term. | |
# Otherwise courses from previous terms that have been extended (still active) | |
# would also be included. This may not be needed in your environment. | |
elif 'T1' in course: continue | |
elif 'T2' in course: continue | |
#edit course titles to remove trimester marker in course title & pull teacher name | |
elif course.startswith('T1') or course.startswith('T2') or course.startswith('T3'): | |
teacher = course[course.rindex('-')+1:] | |
point = '-' + teacher | |
course1 = course[5:].rstrip(point) | |
temp2 = ','.join([course1,teacher]) | |
else: continue | |
#Get desired score data from JSON list | |
for i,val in enumerate(enrollments): | |
enroll_list.append((str((enrollments[i]['computed_current_score'])))) | |
enroll_list.append((str((enrollments[i]['computed_current_grade'])))) | |
#join data in enrollment list together | |
temp3 = ','.join(enroll_list) | |
#join data into final list to prepare for export | |
final = [temp1,temp2,temp3] | |
result = ','.join(final) | |
outFile.write(result + '\n') | |
#Adds to count & prints | |
count += 1 | |
print(count) | |
outFile.close() | |
#stop timer and print final time | |
stop = timeit.default_timer() | |
print((stop-start)/60) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment