rubric
是老師可在批改學生提交作業時使用的範本。Classroom API 可讓您代表老師執行這些評分量表。
圖 1.可查看 Classroom 作業的評分量表範例。
本指南說明 Rubrics API 的基本概念和功能。請參閱這些說明中心文章,瞭解評分量表的一般結構,以及如何透過 Classroom UI 進行評分量表評分。
必要條件
本指南假設您具備下列項目:
- Python 3.8.6 以上版本
- pip 套件管理工具
- Google Cloud 專案。
- 擁有 Google Workspace for Education 帳戶,且已啟用 Google Classroom。
- 包含至少一個測驗學生帳戶的測驗課程。如果您沒有可用來測試的 Classroom 課程,請在 UI 中建立課程並新增測試學生。
授權電腦版應用程式的憑證
如要以使用者身分進行驗證並在應用程式中存取使用者資料,您必須建立一或多個 OAuth 2.0 用戶端 ID。用戶端 ID 可用來向 Google 的 OAuth 伺服器識別單一應用程式。如果應用程式在多個平台上執行,就必須為每個平台建立不同的用戶端 ID。
- 前往 Google Cloud 控制台的 GCP 「憑證」頁面。
- 依序按一下「建立憑證」 >「OAuth 用戶端 ID」。
- 依序點選「應用程式類型」 >「電腦版應用程式」。
- 在「Name」(名稱) 欄位中,輸入憑證名稱。這個名稱只會顯示在 Google Cloud 控制台中。例如「評分量表預覽用戶端」。
- 按一下「建立」,系統隨即會顯示 OAuth 用戶端建立的畫面,顯示新的用戶端 ID 和用戶端密鑰。
- 依序點選「Download JSON」(下載 JSON) 和「OK」(確定)。新建立的憑證會顯示在 OAuth 2.0 用戶端 ID 下方。
- 將下載的 JSON 檔案儲存為
credentials.json
,然後將檔案移至工作目錄。 - 按一下「建立憑證」 >「API 金鑰」,然後記下 API 金鑰。
詳情請參閱「建立存取憑證」一文。
設定 OAuth 範圍
視專案現有的 OAuth 範圍而定,您可能需要設定新增範圍。
- 前往 OAuth 同意畫面。
- 依序按一下「Edit App」 >「Save and Continue」,前往「Scopes」畫面。
- 按一下「新增或移除範圍」。
- 如果您還沒有下列範圍,請先新增:
https://www.googleapis.com/auth/classroom.coursework.students
https://www.googleapis.com/auth/classroom.courses
- 接著,按一下「更新」 >「儲存並繼續」 >「儲存並繼續」 >「返回資訊主頁」。
詳情請參閱「設定 OAuth 同意畫面」。
classroom.coursework.students
範圍可讓您讀取及寫入評分量表 (以及 CourseWork
的存取權),而 classroom.courses
範圍則允許讀取和寫入課程。
特定方法所需的範圍已列在該方法的參考說明文件中。如需範例,請參閱 courses.courseWork.rubrics.create
授權範圍。您可以在 Google API 的 OAuth 2.0 範圍中查看所有 Classroom 範圍。由於這個 API 仍為預先發布版,因此這裡未提及的評分量表。
設定範例
在工作目錄中,安裝 Python 適用的 Google 用戶端程式庫:
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
建立名為 main.py
的檔案,用於建構用戶端程式庫並授權使用者,並使用您的 API 金鑰取代 YOUR_API_KEY
:
import json
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/classroom.courses',
'https://www.googleapis.com/auth/classroom.coursework.students']
def build_authenticated_service(api_key):
"""Builds the Classroom service."""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run.
with open('token.json', 'w') as token:
token.write(creds.to_json())
try:
# Build the Classroom service.
service = build(
serviceName="classroom",
version="v1",
credentials=creds,
discoveryServiceUrl=f"https://classroom.googleapis.com/$discovery/rest?labels=DEVELOPER_PREVIEW&key={api_key}")
return service
except HttpError as error:
print('An error occurred: %s' % error)
if __name__ == '__main__':
service = build_authenticated_service(YOUR_API_KEY)
使用 python main.py
執行指令碼。系統應提示您登入並同意 OAuth 範圍。
建立作業
評分量表與作業 (或 CourseWork
) 相關聯,而且只有在該 CourseWork
環境下才具有意義。只有建立父項 CourseWork
項目的 Google Cloud 專案才能建立評分量表。為達成本指南的目的,請使用指令碼建立新的 CourseWork
指派作業。
請將以下內容新增至 main.py
:
def get_latest_course(service):
"""Retrieves the last created course."""
try:
response = service.courses().list(pageSize=1).execute()
courses = response.get("courses", [])
if not courses:
print("No courses found. Did you remember to create one in the UI?")
return
course = courses[0]
return course
except HttpError as error:
print(f"An error occurred: {error}")
return error
def create_coursework(service, course_id):
"""Creates and returns a sample coursework."""
try:
coursework = {
"title": "Romeo and Juliet analysis.",
"description": """Write a paper arguing that Romeo and Juliet were
time travelers from the future.""",
"workType": "ASSIGNMENT",
"state": "PUBLISHED",
}
coursework = service.courses().courseWork().create(
courseId=course_id, body=coursework).execute()
return coursework
except HttpError as error:
print(f"An error occurred: {error}")
return error
現在更新 main.py
,擷取您剛建立的測試類別的 course_id
、建立新的範例作業,並擷取作業的 coursework_id
:
if __name__ == '__main__':
service = build_authenticated_service(YOUR_API_KEY)
course = get_latest_course(service)
course_id = course.get("id")
course_name = course.get("name")
print(f"'{course_name}' course ID: {course_id}")
coursework = create_coursework(service, course_id)
coursework_id = coursework.get("id")
print(f"Assignment created with ID {coursework_id}")
#TODO(developer): Save the printed course and coursework IDs.
儲存 course_id
和 coursework_id
。所有評分量表 CRUD 作業都需要這些資訊。
您現在應該可以在 Classroom 中使用 CourseWork
範例了。
圖 2. 在 Classroom 中查看作業範例。
建立評分量表
您現在可以開始管理評分量表了。
您可以在 CourseWork
上使用包含完整評分量表物件的 Create
呼叫來建立評分量表 (此時將省略標準和等級的 ID 屬性 (系統會在建立時產生這些屬性)。
在 main.py
中新增下列函式:
def create_rubric(service, course_id, coursework_id):
"""Creates an example rubric on a coursework."""
try:
body = {
"criteria": [
{
"title": "Argument",
"description": "How well structured your argument is.",
"levels": [
{"title": "Convincing",
"description": "A compelling case is made.", "points": 30},
{"title": "Passable",
"description": "Missing some evidence.", "points": 20},
{"title": "Needs Work",
"description": "Not enough strong evidence..", "points": 0},
]
},
{
"title": "Spelling",
"description": "How well you spelled all the words.",
"levels": [
{"title": "Perfect",
"description": "No mistakes.", "points": 20},
{"title": "Great",
"description": "A mistake or two.", "points": 15},
{"title": "Needs Work",
"description": "Many mistakes.", "points": 5},
]
},
{
"title": "Grammar",
"description": "How grammatically correct your sentences are.",
"levels": [
{"title": "Perfect",
"description": "No mistakes.", "points": 20},
{"title": "Great",
"description": "A mistake or two.", "points": 15},
{"title": "Needs Work",
"description": "Many mistakes.", "points": 5},
]
},
]
}
rubric = service.courses().courseWork().rubrics().create(
courseId=course_id, courseWorkId=coursework_id, body=body,
# Specify the preview version. Rubrics CRUD capabilities are
# supported in V1_20231110_PREVIEW and later.
previewVersion="V1_20231110_PREVIEW"
).execute()
print(f"Rubric created with ID {rubric.get('id')}")
return rubric
except HttpError as error:
print(f"An error occurred: {error}")
return error
接著,使用先前取得的 Course
和 CourseWork
ID 更新並執行 main.py
,建立評分量表範例:
if __name__ == '__main__':
service = build_authenticated_service(YOUR_API_KEY)
rubric = create_rubric(service, YOUR_COURSE_ID, YOUR_COURSEWORK_ID)
print(json.dumps(rubric, indent=4))
關於評分量表呈現方式的幾項要點:
- Classroom 使用者介面會反映條件和等級的順序。
- 分數等級 (具有
points
屬性) 必須依遞增或遞減順序排序 (無法隨機排序)。 - 老師可以在 UI 中重新排序條件和得分等級 (而非未計分等級),且會改變資料在資料中的順序。
如要進一步瞭解評分量表結構,請參閱限制一節。
返回使用者介面,您應該會看到作業的評分量表。
圖 3. 可查看 Classroom 作業的評分量表範例。
閱讀評分量表
作業中最多僅能有一個評分量表,因此 List
看起來可能不太直覺,但是如果還沒有評分量表 ID,這個功能將派上用場。如果沒有與 CourseWork
相關聯的評分量表,List
回應會是空白的。
在 main.py
中新增下列函式:
def get_rubric(service, course_id, coursework_id):
"""
Get the rubric on a coursework. There can only be at most one.
Returns null if there is no rubric.
"""
try:
response = service.courses().courseWork().rubrics().list(
courseId=course_id, courseWorkId=coursework_id,
# Specify the preview version. Rubrics CRUD capabilities are
# supported in V1_20231110_PREVIEW and later.
previewVersion="V1_20231110_PREVIEW"
).execute()
rubrics = response.get("rubrics", [])
if not rubrics:
print("No rubric found for this assignment.")
return
rubric = rubrics[0]
return rubric
except HttpError as error:
print(f"An error occurred: {error}")
return error
更新並執行 main.py
以擷取您新增的評分量表:
if __name__ == '__main__':
service = build_authenticated_service(YOUR_API_KEY)
rubric = get_rubric(service, YOUR_COURSE_ID, YOUR_COURSEWORK_ID)
print(json.dumps(rubric, indent=4))
#TODO(developer): Save the printed rubric ID.
請注意評分量表中的 id
屬性,以供後續步驟使用。
有評分量表 ID 後,Get
就能順利運作。在函式中使用 Get
可能如下所示:
def get_rubric(service, course_id, coursework_id, rubric_id):
"""
Get the rubric on a coursework. There can only be at most one.
Returns a 404 if there is no rubric.
"""
try:
rubric = service.courses().courseWork().rubrics().get(
courseId=course_id,
courseWorkId=coursework_id,
id=rubric_id,
# Specify the preview version. Rubrics CRUD capabilities are
# supported in V1_20231110_PREVIEW and later.
previewVersion="V1_20231110_PREVIEW"
).execute()
return rubric
except HttpError as error:
print(f"An error occurred: {error}")
return error
如果沒有評分量表,這項實作會傳回 404。
更新評分量表
如要透過 Patch
呼叫來更新評分量表,由於評分量表的結構複雜,更新作業必須以讀取 - 修改 - 寫入模式完成,其中整個 criteria
屬性已取代。
更新規則如下:
- 條件或等級新增時沒有 ID 會視為「新增項目」。
- 此前缺少的條件或等級會視為「刪除」。
- 現有 ID 但經過修改的資料的條件或層級會視為「編輯」。未經修改的屬性會維持原狀。
- 透過新或不明 ID 提供的條件或等級會視為「錯誤」。
- 新條件和等級的順序會被視為新的 UI 順序 (具有上述限制)。
新增用於更新評分量表的函式:
def update_rubric(service, course_id, coursework_id, rubric_id, body):
"""
Updates the rubric on a coursework.
"""
try:
rubric = service.courses().courseWork().rubrics().patch(
courseId=course_id,
courseWorkId=coursework_id,
id=rubric_id,
body=body,
updateMask='criteria',
# Specify the preview version. Rubrics CRUD capabilities are
# supported in V1_20231110_PREVIEW and later.
previewVersion="V1_20231110_PREVIEW"
).execute()
return rubric
except HttpError as error:
print(f"An error occurred: {error}")
return error
在這個範例中,指定 criteria
欄位可使用 updateMask
進行修改。
然後修改 main.py
,為上述每個更新規則進行變更:
if __name__ == '__main__':
service = build_authenticated_service(YOUR_API_KEY)
# Get the latest rubric.
rubric = get_rubric(service, YOUR_COURSE_ID, YOUR_COURSEWORK_ID)
criteria = rubric.get("criteria")
"""
The "criteria" property should look like this:
[
{
"id": "NkEyMdMyMzM2Nxkw",
"title": "Argument",
"description": "How well structured your argument is.",
"levels": [
{
"id": "NkEyMdMyMzM2Nxkx",
"title": "Convincing",
"description": "A compelling case is made.",
"points": 30
},
{
"id": "NkEyMdMyMzM2Nxky",
"title": "Passable",
"description": "Missing some evidence.",
"points": 20
},
{
"id": "NkEyMdMyMzM2Nxkz",
"title": "Needs Work",
"description": "Not enough strong evidence..",
"points": 0
}
]
},
{
"id": "NkEyMdMyMzM2Nxk0",
"title": "Spelling",
"description": "How well you spelled all the words.",
"levels": [...]
},
{
"id": "NkEyMdMyMzM2Nxk4",
"title": "Grammar",
"description": "How grammatically correct your sentences are.",
"levels": [...]
}
]
"""
# Make edits. This example will make one of each type of change.
# Add a new level to the first criteria. Levels must remain sorted by
# points.
new_level = {
"title": "Profound",
"description": "Truly unique insight.",
"points": 50
}
criteria[0]["levels"].insert(0, new_level)
# Remove the last criteria.
del criteria[-1]
# Update the criteria titles with numeric prefixes.
for index, criterion in enumerate(criteria):
criterion["title"] = f"{index}: {criterion['title']}"
# Resort the levels from descending to ascending points.
for criterion in criteria:
criterion["levels"].sort(key=lambda level: level["points"])
# Update the rubric with a patch call.
new_rubric = update_rubric(
service, YOUR_COURSE_ID, YOUR_COURSEWORK_ID, YOUR_RUBRIC_ID, rubric)
print(json.dumps(new_rubric, indent=4))
現在 Classroom 中應該會顯示老師所做的變更。
圖 4. 更新評分量表的檢視畫面。
查看評分量表已評分的繳交作業
目前 API 無法使用評分量表為學生繳交的作業評分,但您可以在 Classroom UI 中透過評分量表讀取以評分量表批改的提交內容成績。
以學生身分在 Classroom UI 中完成並繳交作業範例。 然後,老師再使用評分量表為作業評分。
圖 5.老師在評分期間查看評分量表。
使用評分量表進行評分的學生「繳交作業」有兩種新屬性:draftRubricGrades
和 assignedRubricGrades
,分別代表老師在草稿和指派評分狀態期間選擇的分數和等級。
此外,即使是在評分前,使用相關評分量表的學生繳交的作業也會包含 rubricId
欄位。這代表與 CourseWork
相關聯的最新評分量表,如果老師刪除並重新建立評分量表,這個值可能會改變。
您可以使用現有的 studentSubmissions.Get
和 studentSubmissions.List
方法查看已評分的繳交項目。
新增以下函式至 main.py
,即可列出學生繳交的作業:
def get_latest_submission(service, course_id, coursework_id):
"""Retrieves the last submission for an assignment."""
try:
response = service.courses().courseWork().studentSubmissions().list(
courseId = course_id,
courseWorkId = coursework_id,
pageSize=1,
# Specify the preview version. Rubrics CRUD capabilities are
# supported in V1_20231110_PREVIEW and later.
previewVersion="V1_20231110_PREVIEW"
).execute()
submissions = response.get("studentSubmissions", [])
if not submissions:
print(
"""No submissions found. Did you remember to turn in and grade
the assignment in the UI?""")
return
submission = submissions[0]
return submission
except HttpError as error:
print(f"An error occurred: {error}")
return error
然後更新並執行 main.py
,即可查看學生繳交的成績。
if __name__ == '__main__':
service = build_authenticated_service(YOUR_API_KEY)
submission = get_latest_submission(
service, YOUR_COURSE_ID, YOUR_COURSEWORK_ID)
print(json.dumps(submission, indent=4))
draftRubricGrades
和 assignedRubricGrades
包含:
- 相應評分量表的
criterionId
。 - 老師為每個準則指派的
points
。這可能是來自所選層級,但老師也有可能覆寫了這項設定。 - 為每個條件選擇的等級
levelId
。如果老師沒有選擇等級,但仍為準則指派分數,系統就不會顯示這個欄位。
這些清單僅會根據老師選取等級或設定分數的條件,提供項目。舉例來說,如果老師在評分期間選擇只與一個準則互動,則 draftRubricGrades
和 assignedRubricGrades
只會有一個項目,即使評分量表有多個條件也一樣。
刪除評分量表
您可以透過標準 Delete
要求刪除評分量表。下列程式碼顯示的是函式範例以達到完整性,但由於評分已開始,因此您無法刪除目前的評分量表:
def delete_rubric(service, course_id, coursework_id, rubric_id):
"""Deletes the rubric on a coursework."""
try:
service.courses().courseWork().rubrics().delete(
courseId=course_id,
courseWorkId=coursework_id,
id=rubric_id,
# Specify the preview version. Rubrics CRUD capabilities are
# supported in V1_20231110_PREVIEW and later.
previewVersion="V1_20231110_PREVIEW"
).execute()
except HttpError as error:
print(f"An error occurred: {error}")
return error
匯出及匯入評分量表
評分量表可手動匯出至 Google 試算表,供老師重複使用。
除了在程式碼中指定評分量表條件外,您也可以在評分量表主體 (而非 criteria
) 中指定 sourceSpreadsheetId
,以從這些匯出的工作表建立及更新評分量表:
def create_rubric_from_sheet(service, course_id, coursework_id, sheet_id):
"""Creates an example rubric on a coursework."""
try:
body = {
"sourceSpreadsheetId": sheet_id
}
rubric = service.courses().courseWork().rubrics().create(
courseId=course_id, courseWorkId=coursework_id, body=body,
# Specify the preview version. Rubrics CRUD capabilities are
# supported in V1_20231110_PREVIEW and later.
previewVersion="V1_20231110_PREVIEW"
).execute()
print(f"Rubric created with ID {rubric.get('id')}")
return rubric
except HttpError as error:
print(f"An error occurred: {error}")
return error
意見回饋
如果您發現任何問題或想法,可以提供意見回饋。