附件成績和成績回傳式曝光

這是 Classroom 外掛程式系列操作的第六逐步操作說明。

在本逐步操作說明中,您將修改上一個逐步操作說明步驟中的範例,以產生「已評分」的活動類型附件。您也可以透過程式輔助方式將成績傳回 Google Classroom,做為暫定成績顯示在老師的成績單中。

本逐步操作說明與本系列其他單元略有不同,說明將成績傳回 Classroom 的方法有兩種。兩者對開發人員和使用者體驗都有不同的影響,因此在設計 Classroom 外掛程式時,都需考慮這兩項因素。如要進一步瞭解實作選項,請參閱與附件互動指南頁面

請注意,API 的評分功能為選用項目。可與任何活動類型附件搭配使用。

在本逐步操作說明中,您將完成下列步驟:

  • 修改 Classroom API 先前的連結建立要求,一併設定連結的成績分母。
  • 透過程式輔助方式為學生的繳交內容評分,並設定附件的成績分子。
  • 導入兩種方法,使用學生登入或離線的老師憑證,將提交的成績傳送至 Classroom。

完成後,觸發回傳行為後,成績就會顯示在 Classroom 成績單中。發生的確切情況取決於實作方法。

為了達到此範例的目的,請重複使用上一個逐步操作說明中的活動,其中學生會看到知名地標的圖片,並提示他們輸入名稱。如果學生輸入正確的名稱,請為附件指派完整標記,否則為零。

瞭解 Classroom 外掛程式 API 評分功能

您的外掛程式可以設定附件的成績分子和成績分母。請使用 API 中的 pointsEarnedmaxPoints 值分別進行設定。如果已設定 maxPoints 值,Classroom UI 中的附件資訊卡就會顯示。

一項作業含有 maxPoints 的多個附件範例

圖 1 指派作業建立 UI,內含三個已設定 maxPoints 的外掛程式附件資訊卡。

Classroom 外掛程式 API 可讓您調整設定,以及設定附件成績所獲得的分數。這些成績與指派成績不同。不過,作業成績設定會遵循附件評分設定,該附件的附件資訊卡上有「成績同步處理」標籤。如果「成績同步處理」附件將學生繳交的作業設為 pointsEarned,也會設定學生的作業暫定成績。

通常,新增至設定 maxPoints 的作業的第一個附件會接收「成績同步處理」標籤。如需「成績同步處理」標籤的範例,請參閱圖 1 中顯示的作業建立 UI 範例。請注意,「附件 1」資訊卡有「成績同步」標籤,而紅色方塊中的作業成績已更新為 50 分。另請注意,雖然圖 1 顯示了三張附件資訊卡,但只有一張資訊卡含有「成績同步處理」標籤。這是目前實作的一項重要限制:只有一個附件可加上「成績同步」標籤

如果有多個附件設定了 maxPoints,移除含有「成績同步處理」的連結時,系統「不會」為任何其餘附件啟用「成績同步處理」功能。新增另一個設定 maxPoints 的附件後,新附件就會啟用成績同步處理功能,且總成績上限會配合調整。您無法透過程式查看哪些附件含有「成績同步」標籤,也無法查看特定作業包含的附件數量。

設定附件的最高成績

本節說明如何設定附件成績的「分母」,也就是所有學生在提交作業時可達到的最高分數。方法是設定連結的 maxPoints 值。

您只需要稍微修改現有的實作方式,即可啟用評分功能。建立連結時,請在包含 studentWorkReviewUriteacherViewUri 和其他連結欄位的相同 AddOnAttachment 物件中新增 maxPoints 值。

請注意,新作業的預設最高分數是 100 分。建議您將 maxPoints 設為 100 以外的值,以便確認成績設定正確無誤。將 maxPoints 設為 50 做為示範:

Python

建構 attachment 物件時新增 maxPoints 欄位,然後再向 courses.courseWork.addOnAttachments 端點發出 CREATE 要求。您可以在 webapp/attachment_routes.py 檔案中找到這個編號 (如提供的範例所示)。

attachment = {
    # Specifies the route for a teacher user.
    "teacherViewUri": {
        "uri":
            flask.url_for(
                "load_activity_attachment",
                _scheme='https',
                _external=True),
    },
    # Specifies the route for a student user.
    "studentViewUri": {
        "uri":
            flask.url_for(
                "load_activity_attachment",
                _scheme='https',
                _external=True)
    },
    # Specifies the route for a teacher user when the attachment is
    # loaded in the Classroom grading view.
    "studentWorkReviewUri": {
        "uri":
            flask.url_for(
                "view_submission", _scheme='https', _external=True)
    },
    # Sets the maximum points that a student can earn for this activity.
    # This is the denominator in a fractional representation of a grade.
    "maxPoints": 50,
    # The title of the attachment.
    "title": f"Attachment {attachment_count}",
}

為符合本示範的目的,您也可以將 maxPoints 值儲存在本機附件資料庫中,這樣就不必在評分學生繳交的作業時發出額外的 API 呼叫。但請注意,老師可能會單獨更改作業成績設定,而不受外掛程式的影響。將 GET 要求傳送至 courses.courseWork 端點,即可查看指派層級的 maxPoints 值。執行此作業時,請在 CourseWork.id 欄位中傳遞 itemId

現在請更新資料庫模型,讓它一併保存連結的 maxPoints 值。建議您使用 CREATE 回應中的 maxPoints 值:

Python

首先,在 Attachment 資料表中新增 max_points 欄位。您可以依照我們提供的範例,在 webapp/models.py 檔案中找到此資訊。

# Database model to represent an attachment.
class Attachment(db.Model):
    # The attachmentId is the unique identifier for the attachment.
    attachment_id = db.Column(db.String(120), primary_key=True)

    # The image filename to store.
    image_filename = db.Column(db.String(120))

    # The image caption to store.
    image_caption = db.Column(db.String(120))

    # The maximum number of points for this activity.
    max_points = db.Column(db.Integer)

返回 courses.courseWork.addOnAttachments CREATE 要求。儲存回應中傳回的 maxPoints 值。

new_attachment = Attachment(
    # The new attachment's unique ID, returned in the CREATE response.
    attachment_id=resp.get("id"),
    image_filename=key,
    image_caption=value,
    # Store the maxPoints value returned in the response.
    max_points=int(resp.get("maxPoints")))
db.session.add(new_attachment)
db.session.commit()

附件的成績已達上限。您現在應該能夠測試這個行為;在新作業中新增附件,並觀察附件資訊卡上是否顯示「成績同步」標籤和作業的「分數」值發生變化。

在 Classroom 中設定學生繳交成績

本節說明如何設定附件成績的「分子」,也就是個別學生對附件的分數。方法是設定學生提交作業的 pointsEarned 值。

現在您已經有決定性的重要決定:外掛程式應該如何發出設定 pointsEarned 的要求?

問題在於設定 pointsEarned 需要 teacher OAuth 範圍。您不應將 teacher 範圍授予學生使用者;這可能會導致學生與您的外掛程式互動,例如載入老師檢視畫面 iframe,而非學生檢視畫面 iframe。因此,您有兩種方式可以設定 pointsEarned

  • 使用老師已登入的憑證。
  • 使用已儲存的 (離線) 老師憑證。

以下各節說明在示範各項實作方式前,每種方法的優缺點。請注意,我們提供的範例示範了將成績傳送至 Classroom 的「兩種」方法。請參閱以下各語言的操作說明,瞭解如何在執行提供的範例時選擇方法:

Python

請在 webapp/attachment_routes.py 檔案頂端找到 SET_GRADE_WITH_LOGGED_IN_USER_CREDENTIALS 宣告。將這個值設為 True,即可使用登入的老師憑證回傳成績。將這個值設為 False,即可在學生提交活動時,使用已儲存的憑證回傳成績。

使用老師登入的憑證設定成績

使用已登入的使用者憑證發出要求,以便設定 pointsEarned。這看起來應該要相當直覺,因為可反映到目前為止的其餘實作項目,而且不太容易瞭解。

不過,請注意,老師「只會」在學生作業審查 iframe 中與學生的提交內容互動。這有一些重要影響:

  • 除非老師在 Classroom UI 中採取動作,否則系統不會在 Classroom 中填入成績。
  • 教師可能需要開啟所有學生繳交的作業,才能填入所有學生的成績。
  • Classroom 收到成績後,在 Classroom UI 中顯示成績時,會有短暫延遲。延遲時間通常為 5 到 10 秒,但可長達 30 秒。

將這些因素組合起來,表示教師可能需要耗費大量時間的人工作業,才能完整填入整個課程的成績。

如要實作這個方法,請在現有的學生作業審查路徑中另外新增一個 API 呼叫。

擷取學生繳交的作業和附件記錄後,請評估學生繳交的內容並儲存產生的成績。請在 AddOnAttachmentStudentSubmission 物件pointsEarned 欄位中設定成績。最後,在要求主體中使用 AddOnAttachmentStudentSubmission 例項向 courses.courseWork.addOnAttachments.studentSubmissions 端點發出 PATCH 要求。請注意,我們也需要在 PATCH 要求中的 updateMask 中指定 pointsEarned

Python

# Look up the student's submission in our database.
student_submission = Submission.query.get(flask.session["submissionId"])

# Look up the attachment in the database.
attachment = Attachment.query.get(student_submission.attachment_id)

grade = 0

# See if the student response matches the stored name.
if student_submission.student_response.lower(
) == attachment.image_caption.lower():
    grade = attachment.max_points

# Create an instance of the Classroom service.
classroom_service = ch._credential_handler.get_classroom_service()

# Build an AddOnAttachmentStudentSubmission instance.
add_on_attachment_student_submission = {
    # Specifies the student's score for this attachment.
    "pointsEarned": grade,
}

# Issue a PATCH request to set the grade numerator for this attachment.
patch_grade_response = classroom_service.courses().courseWork(
).addOnAttachments().studentSubmissions().patch(
    courseId=flask.session["courseId"],
    itemId=flask.session["itemId"],
    attachmentId=flask.session["attachmentId"],
    submissionId=flask.session["submissionId"],
    # updateMask is a list of fields being modified.
    updateMask="pointsEarned",
    body=add_on_attachment_student_submission).execute()

使用老師離線憑證設定成績

設定成績的第二種方法需要為建立該附件的老師使用「已儲存的憑證」。這個實作要求您必須使用先前授權老師的重新整理和存取權杖建構憑證,然後使用這些憑證設定 pointsEarned

這種做法的一大優點是,在 Classroom UI 中填入成績時,老師無須執行任何操作,即可避免發生上述的問題。如此一來,使用者就能以流暢有效的方式感受評分體驗。此外,這個方法可讓您選擇要回傳成績的時間點,例如學生完成活動或非同步操作。

請完成下列工作來實作此方法:

  1. 修改使用者資料庫記錄,以儲存存取權杖。
  2. 修改附件資料庫記錄以儲存老師 ID。
  3. 擷取老師的憑證,並視需要建構新的 Classroom 服務執行個體。
  4. 設定作業的成績。

為方便示範,請在學生完成活動時設定成績,也就是學生透過「學生檢視」路徑提交表單時。

修改使用者資料庫記錄,儲存存取權杖

如要進行 API 呼叫,您必須具備兩個不重複的權杖,分別是「更新權杖」和「存取權杖」。如果您已按照逐步操作說明系列操作,則 User 資料表結構定義應該已經儲存更新權杖。只有使用已登入的使用者進行 API 呼叫時,就很適合儲存更新權杖,因為您會在驗證流程中收到存取權杖。

不過,您現在必須透過登入使用者以外的身分進行呼叫,因此驗證流程無法使用。因此,您需要一併儲存存取權杖和更新權杖。更新 User 資料表結構定義,加入存取權杖:

Python

在提供的範例中,它位於 webapp/models.py 檔案中。

# Database model to represent a user.
class User(db.Model):
    # The user's identifying information:
    id = db.Column(db.String(120), primary_key=True)
    display_name = db.Column(db.String(80))
    email = db.Column(db.String(120), unique=True)
    portrait_url = db.Column(db.Text())

    # The user's refresh token, which will be used to obtain an access token.
    # Note that refresh tokens will become invalid if:
    # - The refresh token has not been used for six months.
    # - The user revokes your app's access permissions.
    # - The user changes passwords.
    # - The user belongs to a Google Cloud organization
    #   that has session control policies in effect.
    refresh_token = db.Column(db.Text())

    # An access token for this user.
    access_token = db.Column(db.Text())

然後更新任何會建立或更新 User 記錄的程式碼,以儲存存取權杖:

Python

在提供的範例中,它位於 webapp/credential_handler.py 檔案中。

def save_credentials_to_storage(self, credentials):
    # Issue a request for the user's profile details.
    user_info_service = googleapiclient.discovery.build(
        serviceName="oauth2", version="v2", credentials=credentials)
    user_info = user_info_service.userinfo().get().execute()
    flask.session["username"] = user_info.get("name")
    flask.session["login_hint"] = user_info.get("id")

    # See if we have any stored credentials for this user. If they have used
    # the add-on before, we should have received login_hint in the query
    # parameters.
    existing_user = self.get_credentials_from_storage(user_info.get("id"))

    # If we do have stored credentials, update the database.
    if existing_user:
        if user_info:
            existing_user.id = user_info.get("id")
            existing_user.display_name = user_info.get("name")
            existing_user.email = user_info.get("email")
            existing_user.portrait_url = user_info.get("picture")

        if credentials and credentials.refresh_token is not None:
            existing_user.refresh_token = credentials.refresh_token
            # Update the access token.
            existing_user.access_token = credentials.token

    # If not, this must be a new user, so add a new entry to the database.
    else:
        new_user = User(
            id=user_info.get("id"),
            display_name=user_info.get("name"),
            email=user_info.get("email"),
            portrait_url=user_info.get("picture"),
            refresh_token=credentials.refresh_token,
            # Store the access token as well.
            access_token=credentials.token)

        db.session.add(new_user)

    db.session.commit()

修改附件資料庫記錄來儲存老師 ID

如要為活動設定成績,請呼叫以將 pointsEarned 設為該課程的老師。以下提供幾種方法:

  • 儲存老師憑證和課程 ID 的本機對應。但請注意,一位老師不一定與特定課程有關聯。
  • 向 Classroom API courses 端點發出 GET 要求,取得目前的老師。然後查詢本機使用者記錄,找出相符的老師憑證。
  • 建立外掛程式連結時,請將老師 ID 儲存在本機連結資料庫中。接著,從傳遞至學生檢視畫面 iframe 的 attachmentId 擷取老師憑證。

本範例示範了最後一個選項,因為您在學生完成活動附件時設定成績。

將老師 ID 欄位新增至資料庫的 Attachment 資料表:

Python

在提供的範例中,它位於 webapp/models.py 檔案中。

# Database model to represent an attachment.
class Attachment(db.Model):
    # The attachmentId is the unique identifier for the attachment.
    attachment_id = db.Column(db.String(120), primary_key=True)

    # The image filename to store.
    image_filename = db.Column(db.String(120))

    # The image caption to store.
    image_caption = db.Column(db.String(120))

    # The maximum number of points for this activity.
    max_points = db.Column(db.Integer)

    # The ID of the teacher that created the attachment.
    teacher_id = db.Column(db.String(120))

然後更新任何建立或更新 Attachment 記錄的程式碼,以儲存創作者的 ID:

Python

在以上範例中,這是 webapp/attachment_routes.py 檔案中的 create_attachments 方法。

# Store the attachment by id.
new_attachment = Attachment(
    # The new attachment's unique ID, returned in the CREATE response.
    attachment_id=resp.get("id"),
    image_filename=key,
    image_caption=value,
    max_points=int(resp.get("maxPoints")),
    teacher_id=flask.session["login_hint"])
db.session.add(new_attachment)
db.session.commit()

擷取老師的憑證

找出提供學生檢視畫面 iframe 的路徑。將學生的回覆儲存在本機資料庫後,請立即從本機儲存空間擷取老師的憑證。依據前兩個步驟的準備工作,應該可以簡單明瞭。您也可以使用這些元件,為老師使用者建構新的 Classroom 服務執行個體:

Python

在我們提供的範例中,這是 webapp/attachment_routes.py 檔案的 load_activity_attachment 方法。

# Create an instance of the Classroom service using the tokens for the
# teacher that created the attachment.

# We're assuming that there are already credentials in the session, which
# should be true given that we are adding this within the Student View
# route; we must have had valid credentials for the student to reach this
# point. The student credentials will be valid to construct a Classroom
# service for another user except for the tokens.
if not flask.session.get("credentials"):
    raise ValueError(
        "No credentials found in session for the requested user.")

# Make a copy of the student credentials so we don't modify the original.
teacher_credentials_dict = deepcopy(flask.session.get("credentials"))

# Retrieve the requested user's stored record.
teacher_record = User.query.get(attachment.teacher_id)

# Apply the user's tokens to the copied credentials.
teacher_credentials_dict["refresh_token"] = teacher_record.refresh_token
teacher_credentials_dict["token"] = teacher_record.access_token

# Construct a temporary credentials object.
teacher_credentials = google.oauth2.credentials.Credentials(
    **teacher_credentials_dict)

# Refresh the credentials if necessary; we don't know when this teacher last
# made a call.
if teacher_credentials.expired:
    teacher_credentials.refresh(Request())

# Request the Classroom service for the specified user.
teacher_classroom_service = googleapiclient.discovery.build(
    serviceName=CLASSROOM_API_SERVICE_NAME,
    version=CLASSROOM_API_VERSION,
    discoveryServiceUrl=f"https://classroom.googleapis.com/$discovery/rest?labels=ADD_ONS_ALPHA&key={GOOGLE_API_KEY}",
    credentials=teacher_credentials)

設定繳交作業的成績

本文的程序與使用已登入老師的憑證的程序相同。但請注意,您必須使用上一步擷取的老師憑證發出呼叫:

Python

# Issue a PATCH request as the teacher to set the grade numerator for this
# attachment.
patch_grade_response = teacher_classroom_service.courses().courseWork(
).addOnAttachments().studentSubmissions().patch(
    courseId=flask.session["courseId"],
    itemId=flask.session["itemId"],
    attachmentId=flask.session["attachmentId"],
    submissionId=flask.session["submissionId"],
    # updateMask is a list of fields being modified.
    updateMask="pointsEarned",
    body=add_on_attachment_student_submission).execute()

測試外掛程式

與先前的逐步操作說明類似,建立作業含有活動類型附件的老師身分,並以學生身分提交回應,然後在學生作業審查 iframe 中開啟提交內容。視實作方法而定,成績應該可以在不同時間出現:

  • 如果您選擇在學生完成活動時發還成績,那麼在開啟學生作業審查 iframe 之前,您應該已經在 UI 中看到草稿成績。此外,開啟作業時,學生清單也會顯示這項作業,在「學生作業評論」iframe 旁的「成績」方塊中也顯示。
  • 如果您選擇在老師開啟學生作業評論 iframe 時發還成績,則在 iframe 載入後,成績應該很快就會出現在「成績」方塊中。如上文所述,這項作業最多可能需要 30 秒才能完成。之後,「特定學生」的成績也應該會顯示在其他 Classroom 的成績單檢視畫面中。

確認學生看到的分數正確無誤。

恭喜!您可以進行下一個步驟:在 Google Classroom 以外的地方建立附件