def get_tokens(): id_token = request.args.get('id_token') access_token = request.args.get('access_token') gc = GoogleCredentials() creds, info = gc.get_credential_from_token(id_token, access_token) courses = list_courses(creds) return jsonify({'user': info, 'courses': courses})
def execute_app_script(credentials=None): """Calls the Apps Script API. """ if not credentials: credentials = GoogleCredentials().get_credential_local() service = build('script', 'v1', credentials=credentials) # Call the Apps Script API try: # Create a new project request = {'title': 'My Script'} response = service.projects().create(body=request).execute() # Upload two files to the project request = { 'files': [{ 'name': 'createQuiz', 'type': 'SERVER_JS', 'source': QUIZ_CODE }, { 'name': 'appsscript', 'type': 'JSON', 'source': QUIZ_MANIFEST }] } response = service.projects().updateContent( body=request, scriptId=response['scriptId']).execute() print('https://script.google.com/d/' + response['scriptId'] + '/edit') except errors.HttpError as error: # The API encountered a problem. print(error.content)
def run_app_script(credentials=None, script_id=SCRIPT_ID, function_name="myFunction", params=None): """Calls the Apps Script API. """ # store = oauth_file.Storage('token2.json') # creds = store.get() # if not creds or creds.invalid: # flow = client.flow_from_clientsecrets('client.json', SCOPES) # creds = tools.run_flow(flow, store) if not credentials: credentials = GoogleCredentials().get_credential_local() service = build('script', 'v1', credentials=credentials) # Call the Apps Script API result = [] try: # Create an execution request object. request = {"function": function_name, "parameters": params} response = service.scripts().run(body=request, scriptId=script_id).execute() if 'error' in response: # The API executed, but the script returned an error. # Extract the first (and only) set of error details. The values of # this object are the script's 'errorMessage' and 'errorType', and # an list of stack trace elements. error = response['error']['details'][0] error_msg = "Script error message: {0}".format( error['errorMessage']) logger.error(error_msg) result = {'error': error_msg} if 'scriptStackTraceElements' in error: # There may not be a stacktrace if the script didn't start # executing. #print("Script error stacktrace:") for trace in error['scriptStackTraceElements']: logger.error("\t{0}: {1}".format(trace['function'], trace['lineNumber'])) return result else: # The structure of the result depends upon what the Apps Script # function returns. result = response['response'].get('result', {}) if not result: logger.warning('No result returned!') except errors.HttpError as e: # The API encountered a problem before the script started executing. logger.error("ERROR", e.content) result = {'error': e.content} return result
def get_people(): course_id = request.args.get('course_id') people = request.args.get('people', 0) # students by default gc = GoogleCredentials() creds = gc.get_credential() # RM organization courses result = list_students_teachers(creds, teachers=bool(people), course_id=course_id) return jsonify(result)
def get_sheet(creds=None, sheet=None, range=None): if not creds: creds = GoogleCredentials().get_credential_local() SPREADSHEET_ID = sheet or "1W8m1I_eMccRQ9eGdOaucckmem0Jyf-5cmJzyA3wQB-k" RANGE_NAME = range or 'Student Submissions' service = build('sheets', 'v4', credentials=creds) # Call the Sheets API sheet = service.spreadsheets() result = sheet.values().get(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME).execute() values = result.get('values', []) #print(values) return values
def get_classes(): id_token = request.args.get('id_token') access_token = request.args.get('access_token') gc = GoogleCredentials() if access_token and id_token: creds, info = gc.get_credential_from_token(id_token, access_token) else: creds = gc.get_credential() # RM organization courses info = { 'name': get_config("application_org"), 'email': get_config("application_email") } courses = list_courses(creds) return jsonify({'user': info, 'courses': courses})
def get_sheet(creds=None, sheet_id=None, col_range=None): if not creds: creds = GoogleCredentials().get_credential_local() service = build('sheets', 'v4', credentials=creds) # Call the Sheets API sheet = service.spreadsheets() result = sheet.values().get(spreadsheetId=sheet_id, range=col_range).execute() values = result.get('values', []) #gs = sheet.get(spreadsheetId=sheet_id) #print(gs) return values
def add_course(creds=None): if not creds: creds = GoogleCredentials().get_credential_local() service = build('classroom', 'v1', credentials=creds) course = { 'name': 'Middle School Science', 'section': 'Period 4', 'descriptionHeading': 'Welcome to Mid School Science Class', 'description': """We'll be learning about Mid level Science from a combination of textbooks, guest lectures, and online material. Expect to be excited!""", 'room': '305', 'ownerId': '*****@*****.**', 'courseState': 'PROVISIONED' } course = service.courses().create(body=course).execute() print('Course created: {0} ({1})'.format(course.get('name'), course.get('id')))
def list_course_work(creds=None, course_id="78180851867"): """Shows basic usage of the Classroom API. Prints the names of the first 10 courses the user has access to. """ if not creds: creds = GoogleCredentials().get_credential_local() service = build('classroom', 'v1', credentials=creds) # Call the Classroom API results = service.courses().courseWork().list(courseId=course_id).execute() # print(results) course_works = results.get('courseWork', []) if not course_works: print('No course work found.') else: print('Course Work:') for course in course_works: print("\t", course['id'], course['title'], course['state'], course['workType']) return course_works
def list_student_responses(creds=None, students={}, course_id="78180851867", coursework_id="77680692780"): """Shows basic usage of the Classroom API. Prints the names of the first 10 courses the user has access to. """ if not creds: creds = GoogleCredentials().get_credential_local() service = build('classroom', 'v1', credentials=creds) # Call the Classroom API results = service.courses().courseWork().studentSubmissions().list( courseId=course_id, courseWorkId=coursework_id).execute() #print(results) submissions = results.get('studentSubmissions', []) # print(len(submissions)) if not submissions: print('No submissions found.') else: print('Submissions for ', coursework_id) print("\t", "Student", "\t\t\t\t\t", "State", "\t", "Type", "\t", "Length", "\t\t", "State", "\t", "Grade") for submission in submissions: state_history = {} grade_history = {} history = submission.get('submissionHistory', []) if history: state_history = history[-1].get('stateHistory', {}) grade_history = history[-1].get('gradeHistory', {}) print("\t", students.get(submission["userId"], {}).get("email"), "\t", submission['state'], "\t", submission['courseWorkType'],"\t", len(history), "\t", state_history.get('state'), "\t", grade_history.get('pointsEarned'), "/", grade_history.get('maxPoints')) return submissions
def list_students_teachers(creds=None, teachers=False, course_id="78180851867"): """Shows basic usage of the Classroom API. Prints the names of the first 10 courses the user has access to. """ if not creds: creds = GoogleCredentials().get_credential_local() service = build('classroom', 'v1', credentials=creds) # Call the Classroom API if teachers: results = service.courses().teachers().list( courseId=course_id).execute() # print(results) students = results.get('teachers', []) else: results = service.courses().students().list( courseId=course_id).execute() # print(results) students = results.get('students', []) #print(len(submissions)) student_dict = {} if not students: #print('No ', 'student' if not teachers else 'teacher',' found.') student_dict = {} else: #print('Teachers' if teachers else 'Students:') for student in students: student_dict[student['userId']] = { 'name': student['profile'].get('name'), 'email': student['profile'].get('emailAddress'), 'user_id': student['userId']} #print("\t", student['profile'].get('emailAddress'), # student['profile'].get('name'), # student['userId']) return student_dict
def list_courses(creds=None): """Shows basic usage of the Classroom API. Prints the names of the first 10 courses the user has access to. """ if not creds: creds = GoogleCredentials().get_credential_local() service = build('classroom', 'v1', credentials=creds) # Call the Classroom API results = service.courses().list(pageSize=10).execute() courses = results.get('courses', []) # if not courses: # print('No courses found.') # else: # print('Courses:') # print(courses) # for course in courses: # print("\t", course['id'], course['name'], course['courseState']) return courses
# Call the Apps Script API try: # Create a new project request = {'title': 'My Script'} response = service.projects().create(body=request).execute() # Upload two files to the project request = { 'files': [{ 'name': 'hello', 'type': 'SERVER_JS', 'source': SAMPLE_CODE }, { 'name': 'appsscript', 'type': 'JSON', 'source': SAMPLE_MANIFEST }] } response = service.projects().updateContent( body=request, scriptId=response['scriptId']).execute() print('https://script.google.com/d/' + response['scriptId'] + '/edit') except errors.HttpError as error: # The API encountered a problem. print(error.content) if __name__ == '__main__': initialize_config() creds = GoogleCredentials().get_credential_local() main(creds)
Expect to be excited!""", 'room': '305', 'ownerId': '*****@*****.**', 'courseState': 'PROVISIONED' } course = service.courses().create(body=course).execute() print('Course created: {0} ({1})'.format(course.get('name'), course.get('id'))) if __name__ == '__main__': # creds = get_credential_local() # add_course() creds = GoogleCredentials().get_credential('token2.pickle') courses = list_courses(creds) print("**********************************") for course in courses: course_works = list_course_work(creds, course_id=course['id']) students = list_students_teachers(creds, course_id=course['id']) #print(students) teachers = list_students_teachers(creds, teachers=True, course_id=course['id']) #print(students) print("**********************************") for work in course_works: list_student_responses(creds, students=students,