外部附件和上交

这是 Google 课堂插件演示系列中的第七次演示。

在本演示中,您将向 Web 应用添加从 Google 课堂外部创建插件附件的行为。使用此行为可让您的用户基于现有产品或网站创建插件连接。这也是 CourseWork 集成的有益补充,因为您可以将现有流量定向到插件提供的改进用户体验,无需更改其流程。如需了解建议的流程,请参阅我们的在 Google 课堂之外创建附件指南页面。

您还可以向插件添加行为,以以编程方式修改包含插件附件的分配关系。您可以修改包含您的插件附件的任何作业,无论作业的创建者是谁。这对于在学生完成活动后上交作业尤其有用,可告知教师布置的作业已完成,学生的作业可供批改。

您可以扩展支持内容类型活动类型附件的插件的最终版本。在本指南中,我们将使用内容类型附件。

添加分配管理 OAuth 范围

确保您的应用请求以下范围:

  • https://www.googleapis.com/auth/classroom.addons.teacher
  • https://www.googleapis.com/auth/classroom.addons.student
  • https://www.googleapis.com/auth/classroom.coursework.students

classroom.coursework.students 范围之前不需要,它用于创建或修改 CourseWork 分配。将此范围添加到 Cloud 项目的 Google Workspace Marketplace SDKOAuth 同意屏幕以及服务器代码中的范围列表中。

Python

  SCOPES = [
    "https://www.googleapis.com/auth/classroom.addons.teacher",
    "https://www.googleapis.com/auth/classroom.addons.student",
    "https://www.googleapis.com/auth/classroom.coursework.students",
  ]

在 Google 课堂中创建作业

向非 iframe 网页添加按钮

本演示中介绍的流程可让用户通过非 Google 产品创建 Google 课堂作业和附件。实际上,这可能是您现有的网站或应用。在此示例中,您需要创建一个模拟网页作为外部网站。您需要一个按钮或链接,点击该按钮或链接会打开新路由,以执行建议的 CourseWork 流程来创建新分配。

如果您还没有可以让用户登录的按钮或链接,则还需要添加一个按钮或链接。您将需要用户凭据才能发出后续 API 请求,因此他们必须完成 OAuth 2.0 握手。如需具体指导,请参阅登录演示

Python

提供的 Python 示例修改了第一个演示步骤中引入的 /index 路由。

<!-- /webapp/templates/index.html -->
<a href="clear-credentials.html">Logout</a>
<a href="start-auth-flow.html">Login</a>

<br>

<a href="create-coursework-assignment.html">Create a CourseWork Assignment</a>

添加 HTML 模板来表示网站中的某个目标。此页面表示将要附加到 CourseWork 分配的内容。

<!-- /webapp/templates/example-coursework-assignment.html -->
<h1>CourseWork assignment loaded!</h1>
<p>You've loaded a CourseWork assignment! It was created from an external web page.</p>

创建新的 Python 模块文件来处理与 CourseWork 相关的路由。 这是我们提供的示例中的 coursework_routes.py。添加以下三个路由;请注意,您稍后会填写部分内容。

# /webapp/coursework_routes.py
@app.route("/create-coursework-assignment")
def create_coursework_assignment():
  """
  Completes the assignment creation flow.
  """

  # Check that the user is signed in. If not, perform the OAuth 2.0
  # authorization flow.
  credentials = get_credentials()

  if not credentials:
    return start_auth_flow("coursework_assignment_callback")

  # Construct the Google Classroom service.
  classroom_service = get_classroom_service()

  pass  # To be completed later.

@app.route("/example-coursework-assignment/<assignment_type>")
def example_coursework_assignment(assignment_type):
  """
  Renders the "example-coursework-assignment.html" template.
  """
  return flask.render_template(
      "example-coursework-assignment.html", assignment_type=assignment_type
  )

@app.route("/coursework-assignment-callback")
def coursework_assignment_callback():
  """
  Completes the OAuth 2.0 handshake and stores credentials in the session.
  This is identical to the callback introduced in the sign-in walkthrough,
  but redirects the user to the index page instead of the attachment
  discovery page.
  """
  flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
      CLIENT_SECRETS_FILE,
      scopes=SCOPES,
      state=flask.session["state"],
      redirect_uri=flask.url_for("coursework_assignment_callback", _external=True),
  )

  flow.fetch_token(authorization_response=flask.request.url)

  credentials = flow.credentials
  flask.session["credentials"] = session_credentials_to_dict(
      credentials
  )

  # Close the current window and redirect the user to the index page.
  return flask.render_template("close-me.html", redirect_destination="index")

检查用户的插件创建资格

用户必须满足几个前提条件,您才能代表他们创建插件连接。为方便起见,Google 提供了 courses.checkAddOnCreationEligibility 方法来确定用户是否满足这些前提条件。满足这些前提条件的用户称为“符合条件的用户”。

将资格检查添加到 CourseWork 创建路由实现中。然后测试响应中的 isCreateAttachmentEligible 字段。对于符合条件的用户,请按照逻辑创建包含插件连接的分配。否则,请创建链接资料。您需要知道用户想要在其中创建作业的课程的 ID。通常,您会提示用户指定要使用的课程。为简单起见,我们在此示例中使用了硬编码值。

Python

# /webapp/coursework_routes.py
@app.route("/create-coursework-assignment")
def create_coursework_assignment():
  """
  Completes the assignment creation flow.
  """
  # ... Check that the user is signed in and get the Classroom service ...

  # The ID of the course to which the assignment will be added.
  course_id = 1234567890  # TODO(developer) Replace with an actual course ID.

  # Check whether the user can create add-on attachments.
  eligibility_response = (
      classroom_service.courses()
      .checkAddOnCreationEligibility(courseId=course_id)
      .execute()
  )
  is_create_attachment_eligible = eligibility_response.get("isCreateAttachmentEligible")

  if is_create_attachment_eligible:
    # See the "Create an assignment with add-on attachment for eligible users" section for implementation.
  if not is_create_attachment_eligible:
    # See the "Create a Link Material" section for implementation.

为符合条件的用户创建带有插件附件的作业

如果用户有资格创建插件附件,请执行以下操作:

  1. 发送 API 请求以在 Google 课堂中创建不含附件courseWork 作业。
  2. 提取新创建的分配作业的 id
  3. 构造一个新的 CourseWork AddOnAttachment
  4. 发送在 Google 课堂中为新创建的作业创建插件附件的请求。

Python

# /webapp/coursework_routes.py
if is_create_attachment_eligible:
  # Create an assignment.
  coursework = {
      "title": "My CourseWork Assignment with Add-on Attachment",
      "description": "Created using the Classroom CourseWork API.",
      "workType": "ASSIGNMENT",
      "state": "DRAFT",  # Set to 'PUBLISHED' to assign to students.
  }

  # Issue a request to create the assignment.
  create_assignment_response = (
      classroom_service.courses()
      .courseWork()
      .create(courseId=course_id, body=coursework)
      .execute()
  )

  # Create an add-on attachment that links to the selected content and
  # associate it with the new assignment.
  content_url = flask.url_for(
      "example_coursework_assignment",
      assignment_type="add-on-attachment",
      _scheme="https",
      _external=True,
  )

  # Construct an AddOnAttachment instance.
  attachment = {
      "teacherViewUri": {"uri": content_url},
      "studentViewUri": {"uri": content_url},
      "title": f'Test Attachment for Assignment {create_assignment_response.get("id")}',
  }

  # Issue a request to create the attachment.
  add_on_attachment_response = (
      classroom_service.courses()
      .courseWork()
      .addOnAttachments()
      .create(
          courseId=course_id,
          itemId=create_assignment_response.get("id"),  # ID of the new assignment.
          body=attachment,
      )
      .execute()
  )

如果用户没有资格创建插件附件,请改为创建链接资料,具体操作如下:

Python

if not is_create_attachment_eligible:
    coursework = {
        "title": "My CourseWork Assignment with Link Material",
        "description": "Created using the Classroom CourseWork API.",
        "workType": "ASSIGNMENT",
        "state": "DRAFT",  # Set to 'PUBLISHED' to assign to students.
        # Specify the URL for your content as a Link Material.
        "materials": [
            {
                "link": {
                    "url": flask.url_for(
                        "example_coursework_assignment",
                        assignment_type="link-material",
                        _scheme="https",
                        _external=True,
                    )
                }
            }
        ],
    }

    # Issue a request to create the assignment.
    assignment_response = (
        classroom_service.courses()
        .courseWork()
        .create(courseId=course_id, body=coursework)
        .execute()
    )

修改已创建的作业

无论信息流项的创建者是谁,都可以访问、修改、上交、收回或退回包含至少一个插件附件的 Google 课堂信息流项。流项可以是任何 AnnouncementCourseWork 分配或 CourseWorkMaterial

为了演示这一点,您需要添加一个路由来修改给定的流项目。使用此方法验证您能否访问和修改自己使用 API 创建的信息流项以及教师通过 Google 课堂界面创建的信息流项。

再添加一个链接或按钮,指向您在本演示中首次修改的网页。它应该会打开一条新路由来修改 CourseWork 分配。

Python

提供的 Python 示例修改了本演示前面部分修改过的 /index 路由。

<!-- /webapp/templates/index.html -->
<a href="modify-coursework-assignment.html">Create a CourseWork Assignment</a>

创建新路线来处理与 CourseWork 相关的路线。这位于我们提供的示例的 coursework_routes.py 文件中。

# Check that the user is signed in.
credentials = get_credentials()

if not credentials:
  return start_auth_flow("coursework_assignment_callback")

# Get the Google Classroom service.
classroom_service = get_classroom_service()

# The ID of the course to which the assignment will be added.
# Ordinarily, you'll prompt the user to specify which course to use. For
# simplicity, we use a hard-coded value in this example.
course_id = 1234567890  # TODO(developer) Replace with an actual course ID.
assignment_id = 1234567890  # TODO(developer) Replace with an actual assignment ID.

# Retrieve details about the CourseWork assignment.
get_coursework_response = (
    classroom_service.courses()
    .courseWork()
    .get(courseId=course_id, id=assignment_id)
    .execute()
)

# Alter the current title.
assignment_title = f"{get_coursework_response.get('title')} (Modified by API request)"

# Issue a request to modify the assignment.
modify_coursework_response = (
    classroom_service.courses()
    .courseWork()
    .patch(
        courseId=course_id,
        id=assignment_id,
        updateMask="title",
        body={"title": assignment_title},
    )
    .execute()
)

测试插件

为简单起见,所提供的示例使用硬编码的课程和分配标识符。如需获取这些标识符,您可以使用教师凭据向 coursescourseWork 资源的 getlist 方法发出请求。创建 courseWork 分配时,响应中也会返回这些事件。

运行服务器,然后前往索引页面,并在没有 Google Workspace 教育版教与学升级版许可的情况下,以教师用户身份登录。您可以在测试网域的管理控制台中切换用户的许可状态。点击 Create a CourseWork Assignment(创建 CourseWork 作业)按钮,然后打开 Google 课堂界面并验证已创建包含链接 Material 附件的作业。附件应显示链接网页的标题和网址。

测试插件附件的创建情况

返回索引页面,然后以教师用户身份登录(拥有 Google Workspace 教育版教与学版或 Plus 版许可)。点击 Create a CourseWork Assignment(创建 CourseWork 作业)按钮,然后打开 Google 课堂界面并验证是否创建了带有插件附件的作业。附件应显示插件应用的名称和代码中指定的标题。

测试分配修改

请返回索引页面,并确保您已以教师用户身份登录且拥有教与学升级版或 Plus 版许可。点击 Modify a CourseWork Assignment 按钮,然后返回 Google 课堂界面并验证作业标题已更改。

恭喜!您已完成本演示系列。