Python script to publish courses in an account
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
07-20-2018
09:43 AM
Here's a script I just wrote to publish all courses in a specific account. Hopefully someone will find this helpful.
import requests
def chunks(source_list, chunk_size):
"""
Method to split up your list into chunks
Yield successive chunk_size-sized chunks from list.
Source: https://www.datacamp.com/community/tutorials/18-most-common-python-list-questions-learn-python#question11
"""
for i in range(0, len(source_list), chunk_size):
yield source_list[i:i + chunk_size]
def publish_account_courses(base_url, token, sub_account_id):
account_courses_url = base_url + 'accounts/' + str(sub_account_id) + '/courses'
header = {'Authorization': 'Bearer ' + token}
all_course_ids = []
# Get the first page of courses in the sub-account
payload = {
'per_page': 100 # Per page max value appears to be 100
}
response = requests.get(url=account_courses_url, headers=header, data=payload)
courses = response.json()
# Add the course IDs to the list
for course in courses:
all_course_ids.append(course['id'])
# Get the remaining pages of courses, if any
while 'next' in response.links:
# No longer need to include params, the next link has them saved
response = requests.get(url=response.links['next']['url'], headers=header)
courses = response.json()
# Add the course IDs to the list
for course in courses:
all_course_ids.append(course['id'])
# We can only update 500 courses at a time. Need to split up list of course IDs if longer than that
# This is a new list - will contain lists of course IDs no longer than 500 each
course_id_lists = list(chunks(all_course_ids, 500))
for course_list in course_id_lists:
# Take the list of course IDs and pass them to the 'Update courses' endpoint
payload = {
'course_ids[]': course_list,
'event': 'offer' # Offer in the API is the same as Publish in the UI
}
response = requests.put(url=account_courses_url, headers=header, data=payload)
response.raise_for_status()
# I'm not bothering to check the progress of this operation since it's just changing the state
# Canvas environment info
BASE_URL = 'PUT URL HERE'
TOKEN = 'PUT TOKEN HERE'
publish_account_courses(base_url=BASE_URL, token=TOKEN, sub_account_id=8)