Skip to content

Commit dc23d5b

Browse files
Created files for Classroom snippets (googleworkspace#298)
* Made changes in the classroom snippet API. * Created files for Classroom snippets. * Created files for Classroom snippets. * Update classroom_add_alias_new.py * Update classroom_add_student.py * Update classroom_invite_guardian.py Co-authored-by: himanshupr2627 <[email protected]>
1 parent 29ae92e commit dc23d5b

10 files changed

Lines changed: 416 additions & 10 deletions
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
"""Copyright 2022 Google LLC
2+
3+
Licensed under the Apache License, Version 2.0 (the "License");
4+
you may not use this file except in compliance with the License.
5+
You may obtain a copy of the License at
6+
7+
http://www.apache.org/licenses/LICENSE-2.0
8+
9+
Unless required by applicable law or agreed to in writing, software
10+
distributed under the License is distributed on an "AS IS" BASIS,
11+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
See the License for the specific language governing permissions and
13+
limitations under the License.
14+
"""
15+
16+
17+
import google.auth
18+
from googleapiclient.discovery import build
19+
from googleapiclient.errors import HttpError
20+
21+
22+
# [START classroom_add_alias_existing]
23+
def classroom_add_alias_existing(course_id):
24+
"""
25+
Adds alias to existing course with specific course_id.
26+
Load pre-authorized user credentials from the environment.
27+
TODO(developer) - See https://developers.google.com/identity
28+
for guides on implementing OAuth2 for the application.
29+
"""
30+
creds, _ = google.auth.default()
31+
# pylint: disable=maybe-no-member
32+
# [START classroom_existing_alias]
33+
service = build('classroom', 'v1', credentials=creds)
34+
alias = 'd:school_math_101'
35+
course_alias = {
36+
'alias': alias
37+
}
38+
try:
39+
course_alias = service.courses().aliases().create(
40+
courseId=course_id,
41+
body=course_alias).execute()
42+
return course_alias
43+
except HttpError as error:
44+
print(f"An error occurred: {error}")
45+
print('Alias Creation Failed')
46+
return course_alias
47+
# [END classroom_existing_alias]
48+
49+
50+
if __name__ == '__main__':
51+
# Put the course_id of course whose alias needs to be added.
52+
classroom_add_alias_existing(456058313539)
53+
54+
# [END classroom_existing_alias]
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
"""
2+
Copyright 2022 Google LLC
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
"""
16+
17+
import os.path
18+
19+
from google.auth.transport.requests import Request
20+
from google.oauth2.credentials import Credentials
21+
from google_auth_oauthlib.flow import InstalledAppFlow
22+
from googleapiclient.discovery import build
23+
from googleapiclient.errors import HttpError
24+
25+
# [START classroom_new_alias]
26+
27+
SCOPES = ['https://www.googleapis.com/auth/classroom.courses']
28+
29+
30+
def classroom_add_alias_new():
31+
"""
32+
Creates a course with alias specification the user has access to.
33+
The file token.json stores the user's access and refresh tokens, and is
34+
created automatically when the authorization flow completes for
35+
the first time.
36+
Load pre-authorized user credentials from the environment.
37+
TODO(developer) - See https://developers.google.com/identity for
38+
guides on implementing OAuth2 for the application.
39+
"""
40+
# pylint: disable=maybe-no-member
41+
creds = None
42+
if os.path.exists('token.json'):
43+
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
44+
# If there are no (valid) credentials available, let the user log in.
45+
if not creds or not creds.valid:
46+
if creds and creds.expired and creds.refresh_token:
47+
creds.refresh(Request())
48+
else:
49+
flow = InstalledAppFlow.from_client_secrets_file(
50+
'credentials.json', SCOPES)
51+
creds = flow.run_local_server(port=0)
52+
# Save the credentials for the next run
53+
with open('token.json', 'w', encoding="utf8") as token:
54+
token.write(creds.to_json())
55+
56+
alias = 'd:school_physics_333'
57+
course = {
58+
'id': alias,
59+
'name': 'English',
60+
'section': 'Period 2',
61+
'description': 'Course Description',
62+
'room': '301',
63+
'ownerId': 'me'
64+
}
65+
try:
66+
print('-------------')
67+
service = build('classroom', 'v1', credentials=creds)
68+
course = service.courses().create(body=course).execute()
69+
print('====================================')
70+
71+
except HttpError as error:
72+
print('An error occurred: %s' % error)
73+
return course
74+
75+
76+
if __name__ == '__main__':
77+
# pylint: disable=too-many-arguments
78+
# Put the course_id of course whose alias needs to be created.
79+
classroom_add_alias_new()
80+
81+
# [END classroom_new_alias]
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
"""
2+
Copyright 2022 Google LLC
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
16+
"""
17+
from __future__ import print_function
18+
19+
import google.auth
20+
from googleapiclient.discovery import build
21+
from googleapiclient.errors import HttpError
22+
23+
# [START classroom_add_attachment]
24+
25+
26+
def classroom_add_attachment(course_id, coursework_id, submission_id):
27+
"""
28+
Adds attachment to existing course with specific course_id.
29+
Load pre-authorized user credentials from the environment.
30+
TODO(developer) - See https://developers.google.com/identity
31+
for guides on implementing OAuth2 for the application.
32+
"""
33+
creds, _ = google.auth.default()
34+
# pylint: disable=maybe-no-member
35+
request = {
36+
'addAttachments': [
37+
{'link': {'url': 'http://example.com/quiz-results'}},
38+
{'link': {'url': 'http://example.com/quiz-reading'}}
39+
]
40+
}
41+
42+
try:
43+
service = build('classroom', 'v1', credentials=creds)
44+
while True:
45+
coursework = service.courses().courseWork()
46+
coursework.studentSubmissions().modifyAttachments(
47+
courseId=course_id,
48+
courseWorkId=coursework_id,
49+
id=submission_id,
50+
body=request).execute()
51+
52+
except HttpError as error:
53+
print(f"An error occurred: {error}")
54+
55+
56+
if __name__ == '__main__':
57+
# Put the course_id, coursework_id and submission_id of course in which
58+
# attachment needs to be added.
59+
classroom_add_attachment('course_id', 'coursework_id', "me")
60+
# [END classroom_add_attachment]
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
"""Copyright 2022 Google LLC
2+
3+
Licensed under the Apache License, Version 2.0 (the "License");
4+
you may not use this file except in compliance with the License.
5+
You may obtain a copy of the License at
6+
7+
http://www.apache.org/licenses/LICENSE-2.0
8+
9+
Unless required by applicable law or agreed to in writing, software
10+
distributed under the License is distributed on an "AS IS" BASIS,
11+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
See the License for the specific language governing permissions and
13+
limitations under the License."""
14+
15+
# [START classroom_add_teacher]
16+
from __future__ import print_function
17+
18+
import os
19+
20+
from google.auth.transport.requests import Request
21+
from google.oauth2.credentials import Credentials
22+
from google_auth_oauthlib.flow import InstalledAppFlow
23+
from googleapiclient.discovery import build
24+
from googleapiclient.errors import HttpError
25+
26+
SCOPES = ['https://www.googleapis.com/auth/classroom.coursework.students']
27+
28+
29+
def classroom_add_student_new(course_id):
30+
"""
31+
Adds a student to a course, the teacher has access to.
32+
The file token.json stores the user's access and refresh tokens, and is
33+
created automatically when the authorization flow completes for the first
34+
time.
35+
Load pre-authorized user credentials from the environment.
36+
TODO(developer) - See https://developers.google.com/identity for
37+
guides on implementing OAuth2 for the application.
38+
"""
39+
40+
creds = None
41+
# The file token.json stores the user's access and refresh tokens, and is
42+
# created automatically when the authorization flow completes for the first
43+
# time.
44+
if os.path.exists('token.json'):
45+
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
46+
# If there are no (valid) credentials available, let the user log in.
47+
if not creds or not creds.valid:
48+
if creds and creds.expired and creds.refresh_token:
49+
creds.refresh(Request())
50+
else:
51+
flow = InstalledAppFlow.from_client_secrets_file(
52+
'credentials.json', SCOPES)
53+
creds = flow.run_local_server(port=0)
54+
# Save the credentials for the next run
55+
with open('token.json', 'w', encoding="utf8") as token:
56+
token.write(creds.to_json())
57+
58+
enrollment_code = 'abc-def'
59+
student = {
60+
'userId': '[email protected]'
61+
}
62+
try:
63+
service = build('classroom', 'v1', credentials=creds)
64+
student = service.courses().students().create(
65+
courseId=course_id,
66+
enrollmentCode=enrollment_code,
67+
body=student).execute()
68+
print(
69+
'''User {%s} was enrolled as a student in
70+
the course with ID "{%s}"'''
71+
% (student.get('profile').get('name').get('fullName'),
72+
course_id))
73+
return student
74+
except HttpError as error:
75+
print(error)
76+
return error
77+
78+
79+
if __name__ == '__main__':
80+
# Put the course_id of course for which student needs to be added.
81+
classroom_add_student_new(478800920837)
82+
# [END classroom_add_teacher]

classroom/snippets/classroom_add_teacher.py

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,17 +19,12 @@
1919

2020

2121
def classroom_add_teacher(course_id):
22-
"""Shows basic usage of the Classroom API.
23-
Updates the courses names the user has access to.
24-
25-
The file token.json stores the user's access and refresh tokens, and is
26-
created automatically when the authorization flow completes for the first
27-
time.
22+
"""
23+
Adds a teacher to a course with specific course_id.
2824
Load pre-authorized user credentials from the environment.
29-
TODO(developer) - See https://developers.google.com/identity for
30-
guides on implementing OAuth2 for the application."""
31-
32-
""" Adds a teacher to a course. """
25+
TODO(developer) - See https://developers.google.com/identity
26+
for guides on implementing OAuth2 for the application.
27+
"""
3328
creds, _ = google.auth.default()
3429
# pylint: disable=maybe-no-member
3530
service = build('classroom', 'v1', credentials=creds)
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
"""
2+
Copyright 2022 Google LLC
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
16+
"""
17+
from __future__ import print_function
18+
19+
import google.auth
20+
from googleapiclient.discovery import build
21+
from googleapiclient.errors import HttpError
22+
23+
# [START classroom_all_submissions]
24+
25+
26+
def classroom_all_submissions(course_id, user_id):
27+
"""
28+
Creates the list of all submissions of the courses the user has access to.
29+
Load pre-authorized user credentials from the environment.
30+
TODO(developer) - See https://developers.google.com/identity
31+
for guides on implementing OAuth2 for the application.\n"
32+
"""
33+
34+
creds, _ = google.auth.default()
35+
# pylint: disable=maybe-no-member
36+
submissions = []
37+
page_token = None
38+
39+
try:
40+
service = build('classroom', 'v1', credentials=creds)
41+
while True:
42+
coursework = service.courses().courseWork()
43+
response = coursework.studentSubmissions().list(
44+
pageToken=page_token,
45+
courseId=course_id,
46+
courseWorkId="-",
47+
userId=user_id).execute()
48+
submissions.extend(response.get('studentSubmissions', []))
49+
page_token = response.get('nextPageToken', None)
50+
if not page_token:
51+
break
52+
53+
if not submissions:
54+
print('No student submissions found.')
55+
else:
56+
print('Complete list of student Submissions:')
57+
for submission in submissions:
58+
print("%s was submitted at %s" %
59+
(submission.get('id'),
60+
submission.get('creationTime')))
61+
62+
except HttpError as error:
63+
print(f"An error occurred: {error}")
64+
submissions = None
65+
return submissions
66+
67+
68+
if __name__ == '__main__':
69+
# Put the course_id and user_id of course whose list needs to be
70+
# submitted.
71+
classroom_all_submissions(453686957652, 466086979658)
72+
# [END classroom_all_submissions]

classroom/snippets/classroom_create_course.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
"""
1717

1818
# [START classroom_create_course]
19+
1920
from __future__ import print_function
2021

2122
import google.auth

0 commit comments

Comments
 (0)