内容类型附件

这是关于 Google 课堂插件的第四项演示 演示系列视频

在本演示中,您将使用 Google Classroom API 创建 附件。您可以为用户提供路由来查看附件内容。通过 视图因用户在类中的角色而异。本演示涵盖 内容类型附件:不需要学生提交内容。

在本演示中,您完成了以下内容:

  • 检索并使用以下插件查询参数: <ph type="x-smartling-placeholder">
      </ph>
    • addOnToken:传递给附件发现的授权令牌 视图。
    • itemId:CourseWork、CourseWorkMaterial 或 接收插件附件的通知。
    • itemType:“courseWork”或“courseWorkMaterials”或 "announcement"。
    • courseId:Google 课堂课程的唯一标识符 将为其创建作业。
    • attachmentId:Google 课堂为 添加附件。
  • 为内容类型附件实现永久性存储。
  • 提供创建附件、提供教师视图和 学生视图 iframe。
  • 向 Google Classroom 插件 API 发出以下请求: <ph type="x-smartling-placeholder">
      </ph>
    • 创建新附件。
    • 获取插件上下文,用于确定已登录用户是否 学生或教师

完成后,您可以通过 Google 课堂界面(以教师身份登录时)。教师和学生 该类还可以查看内容。

启用 Classroom API

从此步骤开始调用 Classroom API。此 API 必须 必须先为 Google Cloud 项目启用,然后才能调用它。导航 添加到 Google Classroom API 库条目,然后选择启用

处理附件发现视图查询参数

如前所述,Google 课堂会在发生以下情况时传递查询参数: 在 iframe 中加载附件发现视图:

  • courseId:当前 Google 课堂课程的 ID。
  • itemId:CourseWork、CourseWorkMaterial 或 接收插件附件的通知。
  • itemType:“courseWork”或“courseWorkMaterials”或“公告”
  • addOnToken:用于向 Google 课堂插件操作。
  • login_hint:当前用户的 Google ID。

本演示介绍了 courseIditemIditemTypeaddOnToken。 在调用 Classroom API 时保留和传递这些内容。

与上一步一样,将传递的查询参数值存储在 会话。请务必在“附件发现视图” 因为这是 Google 课堂 传递这些查询参数。

Python

导航到为连接提供路由的 Flask 服务器文件 Discovery View(attachment-discovery-routes.py如果您正在关注我们的 提供的示例)。在附加服务着陆路线的顶部 (我们所提供示例中的 /classroom-addon),检索并存储 courseIditemIditemTypeaddOnToken 查询参数。

# Retrieve the itemId, courseId, and addOnToken query parameters.
if flask.request.args.get("itemId"):
    flask.session["itemId"] = flask.request.args.get("itemId")
if flask.request.args.get("itemType"):
    flask.session["itemType"] = flask.request.args.get("itemType")
if flask.request.args.get("courseId"):
    flask.session["courseId"] = flask.request.args.get("courseId")
if flask.request.args.get("addOnToken"):
    flask.session["addOnToken"] = flask.request.args.get("addOnToken")

仅当这些值存在时才将其写入会话;它们不是 如果用户正好返回“附件发现”视图,则会再次通过 而无需关闭 iframe 即可。

为内容类型附件添加永久性存储空间

您需要所有已创建的连接的本地记录。这样,您就可以查询 教师根据 课堂。

Attachment 设置数据库架构。我们提供的示例 显示图片和图片说明的附件。Attachment 包含 以下属性:

  • attachment_id:连接的唯一标识符。分配者 创建 Google 课堂时在响应中返回了 附件。
  • image_filename:要显示的图片的本地文件名。
  • image_caption:与图片一起显示的说明。

Python

扩展前面步骤中的 SQLite 和 flask_sqlalchemy 实现。

导航到您定义了用户表的文件 (models.py) )。在底部添加以下代码 该文件的 User 类下。

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))

将新的 Attachment 类与附件一起导入服务器文件 处理路线。

设置新路由

首先,在我们的应用中设置一些新页面。 这类广告可让用户通过我们的插件创建和查看内容。

添加连接创建路由

您需要提供一些页面,供教师选择内容以及创建附件 请求。实现 /attachment-options 路由以显示内容选项 供教师选择您还需要用于选择内容和 创建确认页面。我们提供的示例包含适用于这些工作负载的模板, 还会显示来自 Classroom API。

请注意,您也可以修改现有的附件发现视图 着陆页显示内容选项,而不是创建新的 /attachment-options 页面。我们建议您创建一个新页面 以便保留第 2 步中实现的 SSO 行为 演示步骤,例如撤消应用权限。这些应能证明 在构建和测试插件时很有用。

教师可以从我们所提供的带有说明文字的一小部分图片中选择 示例。我们提供了四张著名地标的图片,图片说明中 。

Python

在我们提供的示例中,它位于 webapp/attachment_routes.py 文件中。

@app.route("/attachment-options", methods=["GET", "POST"])
def attachment_options():
    """
    Render the attachment options page from the "attachment-options.html"
    template.

    This page displays a grid of images that the user can select using
    checkboxes.
    """

    # A list of the filenames in the static/images directory.
    image_filenames = os.listdir(os.path.join(app.static_folder, "images"))

    # The image_list_form_builder method creates a form that displays a grid
    # of images, checkboxes, and captions with a Submit button. All images
    # passed in image_filenames will be shown, and the captions will be the
    # title-cased filenames.

    # The form must be built dynamically due to limitations in WTForms. The
    # image_list_form_builder method therefore also returns a list of
    # attribute names in the form, which will be used by the HTML template
    # to properly render the form.
    form, var_names = image_list_form_builder(image_filenames)

    # If the form was submitted, validate the input and create the attachments.
    if form.validate_on_submit():

        # Build a dictionary that maps image filenames to captions.
        # There will be one dictionary entry per selected item in the form.
        filename_caption_pairs = construct_filename_caption_dictionary_list(
            form)

        # Check that the user selected at least one image, then proceed to
        # make requests to the Classroom API.
        if len(filename_caption_pairs) > 0:
            return create_attachments(filename_caption_pairs)
        else:
            return flask.render_template(
                "create-attachment.html",
                message="You didn't select any images.",
                form=form,
                var_names=var_names)

    return flask.render_template(
        "attachment-options.html",
        message=("You've reached the attachment options page. "
                "Select one or more images and click 'Create Attachment'."),
        form=form,
        var_names=var_names,
    )

这会生成一个“创建附件”类似于以下内容的页面:

Python 示例内容选择视图

教师可以选择多张图片。为每张图片创建一个附件 教师在 create_attachments 方法中选择的那个模型。

问题附件创建请求

现在,您已经知道了老师想要附加哪些内容, 向 Classroom API 发出创建附件的请求, 分配。在收到 通过 Classroom API 返回错误。

首先,获取 Google 课堂服务的实例:

Python

在我们提供的示例中,它位于 webapp/attachment_routes.py 文件中。

def create_attachments(filename_caption_pairs):
    """
    Create attachments and show an acknowledgement page.

    Args:
        filename_caption_pairs: A dictionary that maps image filenames to
            captions.
    """
    # Get the Google Classroom service.
    classroom_service = googleapiclient.discovery.build(
        serviceName="classroom",
        version="v1",
        credentials=credentials)

courses.courseWork.addOnAttachments 发出 CREATE 请求 端点。针对教师选择的每张图片,首先构建一个 AddOnAttachment 对象

Python

在我们提供的示例中,这是 create_attachments 的延续 方法。

# Create a new attachment for each image that was selected.
attachment_count = 0
for key, value in filename_caption_pairs.items():
    attachment_count += 1

    # Create a dictionary with values for the AddOnAttachment object fields.
    attachment = {
        # Specifies the route for a teacher user.
        "teacherViewUri": {
            "uri":
                flask.url_for(
                    "load_content_attachment", _scheme='https', _external=True),
        },
        # Specifies the route for a student user.
        "studentViewUri": {
            "uri":
                flask.url_for(
                    "load_content_attachment", _scheme='https', _external=True)
        },
        # The title of the attachment.
        "title": f"Attachment {attachment_count}",
    }

必须至少填写 teacherViewUristudentViewUrititle 字段 每个附件的资源 ID。teacherViewUristudentViewUri 表示在 Google Cloud 应用打开附件时 相应的用户类型

将请求正文中的 AddOnAttachment 对象发送给相应的 addOnAttachments 端点。提供 courseIditemIditemTypeaddOnToken 标识符。

Python

在我们提供的示例中,这是 create_attachments 的延续 方法。

# Use the itemType to determine which stream item type the teacher created
match flask.session["itemType"]:
    case "announcements":
        parent = classroom_service.courses().announcements()
    case "courseWorkMaterials":
        parent = classroom_service.courses().courseWorkMaterials()
    case _:
        parent = classroom_service.courses().courseWork()

# Issue a request to create the attachment.
resp = parent.addOnAttachments().create(
    courseId=flask.session["courseId"],
    itemId=flask.session["itemId"],
    addOnToken=flask.session["addOnToken"],
    body=attachment).execute()

在您的本地数据库中为该附件创建条目,以便稍后操作 加载正确的内容。Google 课堂会返回唯一的 id 值 响应创建请求,因此请在 我们将此作为主键, 数据库。另请注意,Google 课堂会通过 attachmentId 查询参数:

Python

在我们提供的示例中,这是 create_attachments 的延续 方法。

# Store the value 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)
db.session.add(new_attachment)
db.session.commit()

此时,请考虑将用户转到确认页面 表明他们已成功创建附件。

允许来自插件的附件

现在是将任意相应地址添加到“允许的附件”的好时机 Google Workspace Marketplace SDK 的应用配置中的“URI 前缀”字段 页面。您的插件只能使用其中一个 URI 前缀创建附件 。这是一项安全措施,有助于降低 中间人攻击

最简单的方法是在此字段中提供顶级域名, 示例 https://example.comhttps://localhost:<your port number>/ 会 使用本地计算机作为网络服务器

为教师和学生视图添加路线

Google 课堂插件可能会在 4 个 iframe 中加载。 因此,您只构建了提供附件发现视图 iframe 的路由。 远。接下来,添加路线,以便同时投放教师和学生视图 iframe。

必须使用教师视图 iframe 才能显示学生的预览 但可以根据需要添加其他信息或修改 功能。

学生视图是每个学生打开课程时向其显示的页面。 插件附件。

在本练习中,请创建一个 /load-content-attachment 同时提供教师和学生视图的路线。使用 Classroom API 方法,以确定在访问该网页时,用户是教师还是学生 。

Python

在我们提供的示例中,它位于 webapp/attachment_routes.py 文件中。

@app.route("/load-content-attachment")
def load_content_attachment():
    """
    Load the attachment for the user's role."""

    # Since this is a landing page for the Teacher and Student View iframes, we
    # need to preserve the incoming query parameters.
    if flask.request.args.get("itemId"):
        flask.session["itemId"] = flask.request.args.get("itemId")
    if flask.request.args.get("itemType"):
        flask.session["itemType"] = flask.request.args.get("itemType")
    if flask.request.args.get("courseId"):
        flask.session["courseId"] = flask.request.args.get("courseId")
    if flask.request.args.get("attachmentId"):
        flask.session["attachmentId"] = flask.request.args.get("attachmentId")

请注意,此时还应对用户进行身份验证。您 此处还应处理 login_hint 查询参数,并将用户转到 授权流程。请参阅讨论的登录指南详细信息 来详细了解此流程。

然后,向与该项匹配的 getAddOnContext 端点发送请求 类型。

Python

在我们提供的示例中,这是 load_content_attachment 方法结合使用。

# Create an instance of the Classroom service.
classroom_service = googleapiclient.discovery.build(
    serviceName="classroom"
    version="v1",
    credentials=credentials)

# Use the itemType to determine which stream item type the teacher created
match flask.session["itemType"]:
    case "announcements":
        parent = classroom_service.courses().announcements()
    case "courseWorkMaterials":
        parent = classroom_service.courses().courseWorkMaterials()
    case _:
        parent = classroom_service.courses().courseWork()

addon_context_response = parent.getAddOnContext(
    courseId=flask.session["courseId"],
    itemId=flask.session["itemId"]).execute()

此方法会返回有关当前用户在类中的角色的信息。 根据用户的角色更改向其呈现的视图。只有 在响应中填充了 studentContextteacherContext 字段 对象。检查这些问题,以确定如何称呼用户。

在任何情况下,您都可以使用 attachmentId 查询参数值来了解哪些 从我们的数据库中检索附件。此查询参数会在 打开教师视图 URI 或学生视图 URI。

Python

在我们提供的示例中,这是 load_content_attachment 方法结合使用。

# Determine which view we are in by testing the returned context type.
user_context = "student" if addon_context_response.get(
    "studentContext") else "teacher"

# Look up the attachment in the database.
attachment = Attachment.query.get(flask.session["attachmentId"])

# Set the text for the next page depending on the user's role.
message_str = f"I see that you're a {user_context}! "
message_str += (
    f"I've loaded the attachment with ID {attachment.attachment_id}. "
    if user_context == "teacher" else
    "Please enjoy this image of a famous landmark!")

# Show the content with the customized message text.
return flask.render_template(
    "show-content-attachment.html",
    message=message_str,
    image_filename=attachment.image_filename,
    image_caption=attachment.image_caption,
    responses=response_strings)

测试插件

如需测试附件的创建情况,请完成以下步骤:

  • 使用以下账号登录 [Google 课堂]: 教师测试用户。
  • 导航至课业标签,然后创建新的作业
  • 点击文本区域下方的插件按钮,然后选择您的插件。 系统会打开 iframe,并且该插件会加载您在设置附件设置 URI (在 Google Workspace Marketplace SDK 的应用配置页面指定)中指定。
  • 选择要附加到作业中的一段内容。
  • 附件创建流程完成后,关闭 iframe。

您应该会在 Google 的作业创建界面中看到附件卡片 Google 课堂。点击卡片即可打开教师视图 iframe 并确认 系统会显示正确的附件。点击分配按钮。

如需测试学生体验,请完成以下步骤:

  • 然后,以学生考试用户的身份登录 Google 课堂 课程。
  • 在“课业”标签页中找到测试作业。
  • 展开作业,然后点击附件卡片以打开“学生视图” iframe。

确认为学生显示正确的附件。

恭喜!您可以随时进行下一步:创建 活动类型的附件