附件成绩和成绩回传

这是 Google 课堂插件演示系列中的第六个演示。

在本演示中,您将修改上一演示步骤中的示例,以生成已评分的活动类型附件。您还可以以编程方式将成绩发回 Google 课堂,相应成绩会以初始成绩显示在教师的成绩册中。

本演示与该系列中的其他演示略有不同,因为目前有两种可能的方法可以将成绩传递回 Google 课堂。两者对开发者和用户体验有显著的影响;请在设计 Google 课堂插件时考虑两者。 如需了解有关实现选项的其他讨论,请参阅我们的“与附件交互”指南页面

请注意,API 中的评分功能是可选的。它们可以与任何 activity 类型的附件结合使用。

在本演示过程中,您将完成以下操作:

  • 修改之前对 Classroom API 的附件创建请求,以便同时设置附件的成绩分母。
  • 以编程方式为学生提交的内容评分,并设置附件的成绩分子。
  • 实施两种方法,使用已登录或离线的教师凭据将提交内容的成绩传递给 Google 课堂。

完成后,成绩会在触发回传行为后显示在 Google 课堂成绩册中。发生这种情况的确切时机取决于实现方法。

出于此示例目的,请重复使用之前演示中的 activity,其中向学生展示了一个著名地标的图片,并提示学生输入其名称。如果学生输入了正确的姓名,请为附件分配全分,否则为 0。

了解 Google 课堂插件 API 评分功能

您的插件可以同时设置连接成绩分子和成绩分母。它们分别使用 API 中的 pointsEarnedmaxPoints 值进行设置。Google 课堂界面中的附件卡片会显示 maxPoints 值(如果已设置)。

关于在一个分配中使用 maxPoint 的多个连接的示例

图 1. 作业创建界面,其中包含三个设置了 maxPoints 的插件附件卡片。

借助 Google 课堂插件 API,您可以配置设置,并设置附加成绩成绩。这些评分与作业的评分不同。但是,作业成绩设置会遵循附件成绩卡上带有成绩同步标签的附件的附件成绩设置。如果“成绩同步”附件为学生提交的作业设置了 pointsEarned,还会设置学生的作业初始成绩。

通常情况下,添加到作业中且设置了 maxPoints 的第一个附件会收到“成绩同步”标签。如需查看“成绩同步”标签的示例,请参阅图 1 所示的作业创建界面示例。请注意,“附件 1”卡片带有“成绩同步”标签,并且红色框中的作业成绩已更新为 50 分。另请注意,尽管图 1 显示了三个附件卡片,但只有一张卡片具有“成绩同步”标签。这是当前实现的关键限制:只能有一个附件带有“成绩同步”标签

如果有多个附件设置了 maxPoints,则使用“Grade sync”移除连接时不会为其余的任何附件启用“Grade Sync”。添加其他附件并设置 maxPoints 会为新附件启用 Grade Sync,并调整作业的最高成绩。您无法以程序化方式查看哪些附件带有“成绩同步”标签,也无法查看特定作业包含的附件数量。

设置附件的最高成绩

本部分介绍了如何设置附件成绩分母,即所有学生在提交作业时可能获得的最高分数。为此,请设置附件的 maxPoints 值。

只需对现有实现稍作修改,即可启用评分功能。创建连接时,请在包含 studentWorkReviewUriteacherViewUri 和其他附件字段的同一 AddOnAttachment 对象中添加 maxPoints 值。

请注意,新作业的默认最高得分为 100。我们建议您将 maxPoints 设置为 100 以外的值,以便验证成绩设置是否正确。演示时,将 maxPoints 设置为 50:

Python

在构建 attachment 对象时,在向 courses.courseWork.addOnAttachments 端点发出 CREATE 请求之前,请添加 maxPoints 字段。如果您按照我们提供的示例操作,可以在 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 调用。但请注意,教师可能会独立于您的插件更改作业成绩设置。向 courses.courseWork 端点发送 GET 请求可查看分配层级的 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()

附件现已达到最高成绩。您现在应该能够测试此行为;向新作业添加附件,并观察附件卡片是否显示“成绩同步”标签且作业的“分数”值发生变化。

在 Google 课堂中设置学生提交的作业成绩

本部分介绍如何设置附件成绩(即单个学生在附件中的分数)分子。为此,请设置学生提交的 pointsEarned 值。

现在,您需要做出一个重要的决定:您的插件应如何发出设置 pointsEarned 的请求

问题在于,设置 pointsEarned 需要 teacher OAuth 范围。您不应向学生用户授予 teacher 范围;这可能会导致学生与您的插件互动时,出现意外行为,例如加载教师视图 iframe(而非学生视图 iframe)。因此,对于如何设置 pointsEarned,您有两种选择:

  • 使用已登录教师的凭据。
  • 使用存储的(离线)教师凭据。

在演示每种实现之前,以下部分将讨论每种方法的利弊。请注意,我们提供的示例演示了向 Google 课堂传递成绩的两种方法;请参阅下文中针对特定语言的说明,了解如何在运行所提供的示例时选择方法:

Python

webapp/attachment_routes.py 文件的顶部找到 SET_GRADE_WITH_LOGGED_IN_USER_CREDENTIALS 声明。将此值设置为 True 即可使用已登录教师的凭据回传成绩。将此值设置为 False 即可在学生提交 activity 时使用存储的凭据回传成绩。

使用已登录教师的凭据设置成绩

使用已登录用户的凭据发出设置 pointsEarned 的请求。这看起来应该非常直观,因为它反映了其余的实现,并且只需很少的努力就能实现。

不过,请注意,教师在“学生作业评价”iframe 中与学生提交的作业进行互动。这样做有一些重要的影响:

  • 教师在 Google 课堂界面中执行操作之前,Google 课堂中不会填充成绩。
  • 教师可能必须打开学生提交的所有作业,才能填充所有学生的成绩。
  • Google 课堂收到成绩之后,成绩要过一段时间才会显示在 Google 课堂界面中。延迟通常为 5 到 10 秒,但最长可达 30 秒。

这些因素的共同作用意味着,教师可能需要执行大量耗时的手动工作才能完整填充课程的成绩。

如需实现此方法,请向现有的“学生作业评审”路线额外添加一个 API 调用。

获取学生提交内容和附件记录后,评估学生提交的内容并存储生成的成绩。在 AddOnAttachmentStudentSubmission 对象pointsEarned 字段中设置成绩。最后,向 courses.courseWork.addOnAttachments.studentSubmissions 端点发出 PATCH 请求,并在请求正文中包含 AddOnAttachmentStudentSubmission 实例。请注意,我们还需要在 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

这种方法的一个关键优势是,无需教师在 Google 课堂界面中执行相关操作即可填充成绩,从而避免了上述问题。因此,最终用户会认为评分体验顺畅而高效。此外,您还可以通过此方法选择发回成绩的时刻,例如学生完成活动或异步进行。

完成以下任务以实现此方法:

  1. 修改用户数据库记录以存储访问令牌。
  2. 修改附件数据库记录以存储教师 ID。
  3. 检索教师的凭据,并(可选)构建新的 Google 课堂服务实例。
  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

如需为 activity 设置成绩,请通过调用将 pointsEarned 设为课程中的教师。有多种方法可以实现这一目标:

  • 存储教师凭据到课程 ID 的本地映射。但请注意,同一位教师可能并不总是与特定课程相关联。
  • 向 Classroom API courses 端点发出 GET 请求,以获取当前教师。然后,查询本地用户记录,以找到匹配的教师凭据。
  • 创建插件附件时,请将教师 ID 存储在本地附件数据库中。然后,从传递给学生视图 iframe 的 attachmentId 中检索教师凭据。

此示例演示了最后一个选项,因为您是在学生完成活动附件时设置成绩。

在数据库的 Attachment 表格中添加教师 ID 字段:

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 的路线。将学生的回复存储到本地数据库后,立即从本地存储空间检索教师的凭据。鉴于前两个步骤中的准备,这应该很简单。您还可以使用它们为教师用户构建 Google 课堂服务的新实例:

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 之前,您应该已经在界面中看到他们的初始成绩。您也可以在打开作业时在学生列表中以及“学生作业批改”iframe 旁边的“成绩”框中看到它。
  • 如果您选择在教师打开“学生作业查看” iframe 时发回成绩,那么该成绩应该在 iframe 加载后不久即会显示在“成绩”框中。如上文所述,此过程最多可能需要 30 秒。 此后,特定学生的成绩也会显示在其他 Google 课堂成绩册视图中。

确认系统向学生显示正确的分数。

恭喜!您可以继续执行下一步:在 Google 课堂之外创建附件