-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsimple_input.py
More file actions
71 lines (57 loc) · 2.06 KB
/
simple_input.py
File metadata and controls
71 lines (57 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# -*- coding: utf-8 -*-
import json
# getpass and input are simple ways to get user input
import getpass
import requests
import pandas as pd
from builtins import input
# Static settings
# Using a base urls is useful for switching between test and production environments easily
BASE_URL = 'https://canvas.ubc.ca'
PER_PAGE = 100
# User input settings
# token should be treated as a password (not visible when typed)
token = None
while not token:
token = getpass.getpass('Enter your access token:')
auth_header = {'Authorization': 'Bearer ' + token} # setup the authorization header to be used later
# require the course state to be provided
course_state = None
while not course_state in ['unpublished', 'available', 'completed', 'deleted']:
course_state = input("Select a course state [unpublished, available, completed, deleted]:")
print("Finding courses...")
print("-----------------------------")
# continue to make requests until all data has been received
page = 1
courses = []
while True:
# request urls should always be based of the base url so they do not
# need to be changed when switching between test and production environments
request_url = BASE_URL + '/api/v1/courses'
params = {
"per_page": str(PER_PAGE),
"page": str(page),
"state[]": [course_state],
"include[]": ['total_students']
}
r = requests.get(request_url, headers=auth_header, params=params)
# always take care to handle request errors
r.raise_for_status() # raise error if 4xx or 5xx
data = r.json()
if len(data) == 0:
break
courses += data
print("Finished processing page: "+str(page))
page+=1
if len(courses) == 0:
print("No courses found to report on.")
exit()
# from here, a simple table is printed out
# using pandas for convenience
print("Report for "+str(len(courses)) + " courses.")
print("-----------------------------")
courses_df = pd.DataFrame(courses)
result = courses_df.to_string(
columns=['id', 'name', 'course_code', 'workflow_state', 'start_at', 'end_at', 'total_students']
)
print(result)