Last active
November 10, 2024 14:33
-
-
Save mcserep/3b25e06c13d16fafeae4aed8b64b9e0a to your computer and use it in GitHub Desktop.
Canvas LMS script to export course assignment/quiz grades into Excel sheets.
This file contains hidden or 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
| """MIT License | |
| Copyright (c) 2024 Mate Cserep, https://mcserep.web.elte.hu/ | |
| Permission is hereby granted, free of charge, to any person obtaining a copy | |
| of this software and associated documentation files (the "Software"), to deal | |
| in the Software without restriction, including without limitation the rights | |
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| copies of the Software, and to permit persons to whom the Software is | |
| furnished to do so, subject to the following conditions: | |
| The above copyright notice and this permission notice shall be included in all | |
| copies or substantial portions of the Software. | |
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
| SOFTWARE. | |
| """ | |
| ### SETTINGS ### | |
| # Base URL of your Canvas instance | |
| base_url = 'https://canvas.elte.hu' | |
| # Create a new token at the '<base_url>/profile/settings' page. | |
| access_token = 'INSERT YOUR ACCESS TOKEN' | |
| # Define the course name part to look for | |
| course_name_match = 'Programming' | |
| ### PROGRAM ### | |
| import requests | |
| import pandas as pd | |
| import numpy as np | |
| import time | |
| class CourseExporter(): | |
| def __init__(self, course): | |
| self.course = course | |
| self.__assignments = 0 | |
| self.__submissions = 0 | |
| def collect(self): | |
| course_name = self.course['course_code'] | |
| print(f'Exporting {course_name} ... ') | |
| self.get_users() | |
| self.get_assignments() | |
| def write(self): | |
| if self.__submissions == 0: | |
| print('Not writing output, would be empty.') | |
| return | |
| course_name = self.course['course_code'] | |
| filename = course_name.replace('/', '_') + '.xlsx' | |
| self.df.to_excel(filename) | |
| print(f'Output written: {filename}') | |
| def get_users(self): | |
| course_id = self.course['id'] | |
| page = 1 | |
| has_more_pages = True | |
| ids = [] | |
| names = [] | |
| while has_more_pages: | |
| response = requests.get(f'{base_url}/api/v1/courses/{course_id}/enrollments', { | |
| 'access_token': access_token, | |
| 'type[]': 'StudentEnrollment', | |
| 'per_page': 50, | |
| 'page': page | |
| }) | |
| response.raise_for_status() | |
| handle_throttling(response) | |
| enrollments = response.json() | |
| page += 1 | |
| has_more_pages = len(enrollments) > 0 | |
| for enrollment in enrollments: | |
| if enrollment['user_id'] not in ids: | |
| ids.append(enrollment['user_id']) | |
| names.append(enrollment['user']['name']) | |
| print(f'Found {len(names)} students'); | |
| self.df = pd.DataFrame({'UserId': ids, 'Name': names}) | |
| self.df.set_index('UserId', inplace = True) | |
| def get_assignments(self): | |
| course_id = self.course['id'] | |
| page = 1 | |
| has_more_pages = True | |
| while has_more_pages: | |
| response = requests.get(f'{base_url}/api/v1/courses/{course_id}/assignments', { | |
| 'access_token': access_token, | |
| 'per_page': 50, | |
| 'page': page | |
| }) | |
| response.raise_for_status() | |
| handle_throttling(response) | |
| assignments = response.json() | |
| page += 1 | |
| has_more_pages = len(assignments) > 0 | |
| for assignment in assignments: | |
| assignment_id = assignment['id'] | |
| assignment_name = assignment['name'] | |
| self.df[assignment_name] = [None] * len(self.df.index) | |
| self.get_submissions(assignment_id, assignment_name) | |
| self.__assignments = self.df.shape[1] - 1 | |
| print(f'Found {self.__assignments} assignments') | |
| self.__submissions = np.sum(self.df.count()) - len(self.df.index) | |
| print(f'Found {self.__submissions} graded submissions') | |
| def get_submissions(self, assignment_id: int, assignment_name: str): | |
| course_id = self.course['id'] | |
| page = 1 | |
| has_more_pages = True | |
| while has_more_pages: | |
| response = requests.get(f'{base_url}/api/v1/courses/{course_id}/assignments/{assignment_id}/submissions', { | |
| 'access_token': access_token, | |
| 'per_page': 50, | |
| 'page': page | |
| }) | |
| response.raise_for_status() | |
| handle_throttling(response) | |
| submissions = response.json() | |
| page += 1 | |
| has_more_pages = len(submissions) > 0 | |
| for submission in submissions: | |
| if submission['grader_id'] is not None: | |
| student_id = submission['user_id'] | |
| self.df.loc[student_id, assignment_name] = submission['score'] | |
| # see: https://canvas.instructure.com/doc/api/file.throttling.html | |
| def handle_throttling(response: requests.Response): | |
| rate_limit = float(response.headers['X-Rate-Limit-Remaining']) | |
| sleep_time = 0 | |
| if rate_limit < 100: | |
| sleep_time = 30 | |
| elif rate_limit < 200: | |
| sleep_time = 15 | |
| if sleep_time > 0: | |
| print(f'Canvas API throttling, waiting {sleep_time} seconds ...', end = ' ', flush = True) | |
| time.sleep(sleep_time) | |
| print(' done') | |
| # main | |
| try: | |
| page = 1 | |
| has_more_pages = True | |
| while has_more_pages: | |
| response = requests.get(f'{base_url}/api/v1/courses', { | |
| 'access_token': access_token, | |
| 'per_page': 50, | |
| 'page': page | |
| }) | |
| response.raise_for_status() | |
| handle_throttling(response) | |
| courses = response.json() | |
| page += 1 | |
| has_more_pages = len(courses) > 0 | |
| for course in courses: | |
| if course_name_match.lower() not in course['course_code'].lower(): | |
| continue | |
| exporter = CourseExporter(course) | |
| exporter.collect() | |
| exporter.write() | |
| print() | |
| except requests.exceptions.RequestException as err: | |
| print('Canvas communication error occurred, HTTP response code: {0}'.format(err.response.status_code)) | |
| print('Response: {0}'.format(err.response.text)) |
This file contains hidden or 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
| certifi==2024.8.30 | |
| charset-normalizer==3.4.0 | |
| et_xmlfile==2.0.0 | |
| idna==3.10 | |
| numpy==2.1.3 | |
| openpyxl==3.1.5 | |
| pandas==2.2.3 | |
| python-dateutil==2.9.0.post0 | |
| pytz==2024.2 | |
| requests==2.32.3 | |
| six==1.16.0 | |
| tzdata==2024.2 | |
| urllib3==2.2.3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment