Quản lý bài tập trong khoá học và điểm

Giao diện người dùng của Lớp học hỗ trợ năm loại Bài tập trên lớp: Bài tập, Bài kiểm tra, câu hỏi có đáp án ngắn, câu hỏi trắc nghiệm và Tài liệu. API Lớp học hiện hỗ trợ ba trong số các loại sau (còn gọi là CourseWorkType dành cho API): Bài tập, câu hỏi trả lời ngắn và câu hỏi trắc nghiệm.

Materials vào CourseWorkType các tài nguyên: Bài tập, câu hỏi có câu trả lời ngắn và câu hỏi trắc nghiệm.

Để sử dụng chức năng này, bạn có thể sử dụng tài nguyên Tìm hiểu bài tập, đại diện cho một Bài tập hoặc Câu hỏi đã được giao cho học viên trong một khoá học cụ thể, bao gồm cả mọi tài liệu và thông tin chi tiết bổ sung, chẳng hạn như ngày đến hạn hoặc điểm tối đa.

Ngoài tài nguyên CourseWork, bạn có thể quản lý các bài tập đã hoàn thành bằng tài nguyên StudentSubmission. Các phần sau đây sẽ mô tả chi tiết hơn về những yếu tố này.

Tạo bài tập

Bạn chỉ có thể tạo bài tập thay mặt cho(các) giáo viên của khoá học. Nếu bạn tìm cách tạo bài tập trong một khoá học thay mặt cho học viên, lỗi 403 PERMISSION_DENIED sẽ xảy ra. Tương tự, quản trị viên miền cũng không thể tạo bài tập cho các khoá học mà họ không giảng dạy và cố gắng thực hiện thông qua API cũng sẽ dẫn đến lỗi 403 PERMISSION_DENIED.

Khi tạo bài tập bằng phương thức courses.courseWork.create, bạn có thể đính kèm đường liên kết dưới dạng materials, như minh hoạ trong mã mẫu dưới đây:

Java

classroom/snippets/src/main/java/CreateCourseWork.java
CourseWork courseWork = null;
try {
  // Create a link to add as a material on course work.
  Link articleLink =
      new Link()
          .setTitle("SR-71 Blackbird")
          .setUrl("https://www.lockheedmartin.com/en-us/news/features/history/blackbird.html");

  // Create a list of Materials to add to course work.
  List<Material> materials = Arrays.asList(new Material().setLink(articleLink));

  /* Create new CourseWork object with the material attached.
  Set workType to `ASSIGNMENT`. Possible values of workType can be found here:
  https://developers.google.com/classroom/reference/rest/v1/CourseWorkType
  Set state to `PUBLISHED`. Possible values of state can be found here:
  https://developers.google.com/classroom/reference/rest/v1/courses.courseWork#courseworkstate */
  CourseWork content =
      new CourseWork()
          .setTitle("Supersonic aviation")
          .setDescription(
              "Read about how the SR-71 Blackbird, the world’s fastest and "
                  + "highest-flying manned aircraft, was built.")
          .setMaterials(materials)
          .setWorkType("ASSIGNMENT")
          .setState("PUBLISHED");

  courseWork = service.courses().courseWork().create(courseId, content).execute();

  /* Prints the created courseWork. */
  System.out.printf("CourseWork created: %s\n", courseWork.getTitle());
} catch (GoogleJsonResponseException e) {
  // TODO (developer) - handle error appropriately
  GoogleJsonError error = e.getDetails();
  if (error.getCode() == 404) {
    System.out.printf("The courseId does not exist: %s.\n", courseId);
  } else {
    throw e;
  }
  throw e;
} catch (Exception e) {
  throw e;
}
return courseWork;

Python

lớp học/snippets/classroom_create_coursework.py
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def classroom_create_coursework(course_id):
  """
  Creates the coursework the user has access to.
  Load pre-authorized user credentials from the environment.
  TODO(developer) - See https://developers.google.com/identity
  for guides on implementing OAuth2 for the application.
  """

  creds, _ = google.auth.default()
  # pylint: disable=maybe-no-member

  try:
    service = build("classroom", "v1", credentials=creds)
    coursework = {
        "title": "Ant colonies",
        "description": """Read the article about ant colonies
                              and complete the quiz.""",
        "materials": [
            {"link": {"url": "http://example.com/ant-colonies"}},
            {"link": {"url": "http://example.com/ant-quiz"}},
        ],
        "workType": "ASSIGNMENT",
        "state": "PUBLISHED",
    }
    coursework = (
        service.courses()
        .courseWork()
        .create(courseId=course_id, body=coursework)
        .execute()
    )
    print(f"Assignment created with ID {coursework.get('id')}")
    return coursework

  except HttpError as error:
    print(f"An error occurred: {error}")
    return error


if __name__ == "__main__":
  # Put the course_id of course whose coursework needs to be created,
  # the user has access to.
  classroom_create_coursework(453686957652)

Kết quả bao gồm một giá trị nhận dạng do máy chủ chỉ định. Giá trị này có thể dùng để tham chiếu đến hoạt động chỉ định trong các yêu cầu API khác.

Để đưa tài liệu được liên kết vào bài tập tạo qua API Lớp học, hãy sử dụng Tài nguyên đường liên kết để chỉ định URL mục tiêu. Lớp học sẽ tự động tìm nạp tiêu đề và hình thu nhỏ. API Lớp học cũng hỗ trợ sẵn các tài liệu trên Google Drive và YouTube, có thể đi kèm với tài nguyên DriveFile hoặc tài nguyên YouTubeVideo theo cách tương tự.

Để chỉ định ngày đến hạn, hãy đặt các trường dueDatedueTime theo giờ UTC tương ứng. Ngày đến hạn phải là một ngày trong tương lai.

Truy xuất bài tập và câu hỏi

Bạn có thể truy xuất bài tập và câu hỏi cho học viên và giáo viên của khoá học tương ứng hoặc cho quản trị viên miền. Để truy xuất một bài tập hoặc câu hỏi cụ thể, hãy sử dụngcourse.courseWork.get. Để truy xuất tất cả bài tập hoặc câu hỏi (có thể tuỳ ý so khớp một số tiêu chí), hãy sử dụngcourses.courseWork.list.

Phạm vi bắt buộc sẽ tuỳ thuộc vào vai trò của người dùng yêu cầu trong khoá học. Nếu người dùng là học viên, hãy sử dụng một trong các phạm vi sau:

  • https://www.googleapis.com/auth/classroom.coursework.me.readonly
  • https://www.googleapis.com/auth/classroom.coursework.me

Nếu người dùng là giáo viên hoặc quản trị viên miền, hãy sử dụng một trong các phạm vi sau:

  • https://www.googleapis.com/auth/classroom.coursework.students.readonly
  • https://www.googleapis.com/auth/classroom.coursework.students

Việc có quyền truy xuất bài tập hoặc câu hỏi không ngụ ý quyền truy cập vào tài liệu hoặc siêu dữ liệu quan trọng. Trong thực tế, điều này có nghĩa là quản trị viên có thể không thấy tên của một tệp đính kèm trên Drive nếu họ không phải là thành viên của khoá học. Nếu bạn muốn cho phép quản trị viên truy cập vào tệp người dùng, hãy xem hướng dẫn uỷ quyền trên toàn miền.

Quản lý câu trả lời của học viên

Tài nguyên StudentSubmission biểu thị bài tập đã hoàn thành và điểm học viên cho một bài tập hoặc câu hỏi. Tài nguyên StudentSubmission được tạo ngầm cho từng học viên khi câu hỏi hoặc bài tập mới được tạo.

Các phần sau giải thích các thao tác phổ biến quản lý bài làm của học viên.

Truy xuất câu trả lời của học viên

Học viên có thể truy xuất bài nộp của riêng mình, giáo viên có thể truy xuất bài nộp cho tất cả học viên trong khoá học của họ, còn quản trị viên miền có thể truy xuất tất cả bài tập đã nộp cho tất cả học viên trong miền của họ. Mỗi bài nộp của học viên sẽ được gán một giá trị nhận dạng. Nếu bạn biết giá trị nhận dạng, hãy sử dụng courses.courseWork.studentSubmissions.get để truy xuất giá trị nhận dạng đó.

Sử dụng phương thức courses.courseWork.studentSubmissions.list để nhận tài nguyên StudentSubmission phù hợp với một số tiêu chí, như trong mẫu sau:

Java

classroom/snippets/src/main/java/ListSubmissions.java
List<StudentSubmission> studentSubmissions = new ArrayList<>();
String pageToken = null;

try {
  do {
    ListStudentSubmissionsResponse response =
        service
            .courses()
            .courseWork()
            .studentSubmissions()
            .list(courseId, courseWorkId)
            .setPageToken(pageToken)
            .execute();

    /* Ensure that the response is not null before retrieving data from it to avoid errors. */
    if (response.getStudentSubmissions() != null) {
      studentSubmissions.addAll(response.getStudentSubmissions());
      pageToken = response.getNextPageToken();
    }
  } while (pageToken != null);

  if (studentSubmissions.isEmpty()) {
    System.out.println("No student submission found.");
  } else {
    for (StudentSubmission submission : studentSubmissions) {
      System.out.printf(
          "Student id (%s), student submission id (%s)\n",
          submission.getUserId(), submission.getId());
    }
  }
} catch (GoogleJsonResponseException e) {
  // TODO (developer) - handle error appropriately
  GoogleJsonError error = e.getDetails();
  if (error.getCode() == 404) {
    System.out.printf(
        "The courseId (%s) or courseWorkId (%s) does not exist.\n", courseId, courseWorkId);
  } else {
    throw e;
  }
} catch (Exception e) {
  throw e;
}
return studentSubmissions;

Python

lớp học/snippets/classroom_list_submissions.py
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def classroom_list_submissions(course_id, coursework_id):
  """
  Creates the courses the user has access to.
  Load pre-authorized user credentials from the environment.
  TODO(developer) - See https://developers.google.com/identity
  for guides on implementing OAuth2 for the application.
  """

  creds, _ = google.auth.default()
  # pylint: disable=maybe-no-member
  submissions = []
  page_token = None

  try:
    service = build("classroom", "v1", credentials=creds)
    while True:
      coursework = service.courses().courseWork()
      response = (
          coursework.studentSubmissions()
          .list(
              pageToken=page_token,
              courseId=course_id,
              courseWorkId=coursework_id,
              pageSize=10,
          )
          .execute()
      )
      submissions.extend(response.get("studentSubmissions", []))
      page_token = response.get("nextPageToken", None)
      if not page_token:
        break

    if not submissions:
      print("No student submissions found.")

    print("Student Submissions:")
    for submission in submissions:
      print(
          "Submitted at:"
          f"{(submission.get('id'), submission.get('creationTime'))}"
      )

  except HttpError as error:
    print(f"An error occurred: {error}")
    submissions = None
  return submissions


if __name__ == "__main__":
  # Put the course_id and coursework_id of course whose list needs to be
  # submitted.
  classroom_list_submissions(453686957652, 466086979658)

Truy xuất các tài nguyên StudentSubmission thuộc về một học viên cụ thể bằng cách chỉ định tham số userId, như trong mẫu sau:

Java

classroom/snippets/src/main/java/ListStudentSubmissions.java
List<StudentSubmission> studentSubmissions = new ArrayList<>();
String pageToken = null;

try {
  do {
    // Set the userId as a query parameter on the request.
    ListStudentSubmissionsResponse response =
        service
            .courses()
            .courseWork()
            .studentSubmissions()
            .list(courseId, courseWorkId)
            .setPageToken(pageToken)
            .set("userId", userId)
            .execute();

    /* Ensure that the response is not null before retrieving data from it to avoid errors. */
    if (response.getStudentSubmissions() != null) {
      studentSubmissions.addAll(response.getStudentSubmissions());
      pageToken = response.getNextPageToken();
    }
  } while (pageToken != null);

  if (studentSubmissions.isEmpty()) {
    System.out.println("No student submission found.");
  } else {
    for (StudentSubmission submission : studentSubmissions) {
      System.out.printf("Student submission: %s.\n", submission.getId());
    }
  }

Python

classroom/snippets/classroom_list_student_submissions.py
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def classroom_list_student_submissions(course_id, coursework_id, user_id):
  """
  Creates the courses the user has access to.
  Load pre-authorized user credentials from the environment.
  TODO(developer) - See https://developers.google.com/identity
  for guides on implementing OAuth2 for the application.
  """

  creds, _ = google.auth.default()
  # pylint: disable=maybe-no-member
  submissions = []
  page_token = None

  try:
    service = build("classroom", "v1", credentials=creds)
    while True:
      coursework = service.courses().courseWork()
      response = (
          coursework.studentSubmissions()
          .list(
              pageToken=page_token,
              courseId=course_id,
              courseWorkId=coursework_id,
              userId=user_id,
          )
          .execute()
      )
      submissions.extend(response.get("studentSubmissions", []))
      page_token = response.get("nextPageToken", None)
      if not page_token:
        break

    if not submissions:
      print("No student submissions found.")

    print("Student Submissions:")
    for submission in submissions:
      print(
          "Submitted at:"
          f"{(submission.get('id'), submission.get('creationTime'))}"
      )

  except HttpError as error:
    print(f"An error occurred: {error}")
  return submissions


if __name__ == "__main__":
  # Put the course_id, coursework_id and user_id of course whose list needs
  # to be submitted.
  classroom_list_student_submissions(453686957652, 466086979658, "me")

Học viên được xác định bằng mã nhận dạng hoặc địa chỉ email duy nhất của người dùng, do SDK dành cho quản trị viên của Google trả về. Người dùng hiện tại cũng có thể tham chiếu đến mã nhận dạng của chính họ bằng cách viết tắt "me".

Bạn cũng có thể nhận bài tập của học viên cho tất cả các bài tập trong một khoá học. Để thực hiện việc này, hãy sử dụng "-" cố định làm courseWorkId, như trong mẫu sau:

Java

service.courses().courseWork().studentSubmissions()
    .list(courseId, "-")
    .set("userId", userId)
    .execute();

Python

service.courses().courseWork().studentSubmissions().list(
    courseId=<course ID or alias>,
    courseWorkId='-',
    userId=<user ID>).execute()

Phạm vi bắt buộc sẽ tuỳ thuộc vào vai trò của người dùng yêu cầu trong khoá học. Hãy dùng phạm vi sau nếu người dùng là giáo viên hoặc quản trị viên miền:

  • https://www.googleapis.com/auth/classroom.coursework.students.readonly
  • https://www.googleapis.com/auth/classroom.coursework.students

Hãy sử dụng phạm vi sau nếu người dùng là học viên:

  • https://www.googleapis.com/auth/classroom.coursework.me.readonly
  • https://www.googleapis.com/auth/classroom.coursework.me

Việc có quyền truy xuất bài tập mà học viên đã nộp không ngụ ý quyền truy cập vào các tệp đính kèm hoặc siêu dữ liệu của tệp đính kèm. Trong thực tế, điều này có nghĩa là quản trị viên có thể không thấy tên của một tệp đính kèm trên Drive nếu họ không phải là thành viên của khoá học. Nếu bạn muốn cho phép quản trị viên truy cập vào tệp của người dùng, hãy xem hướng dẫn uỷ quyền trên toàn miền.

Thêm tệp đính kèm vào câu trả lời của học viên

Bạn có thể đính kèm đường liên kết vào bài nộp của học viên bằng cách đính kèm tài nguyên Link, DriveFile hoặc YouTubeVideo. Bạn có thể thực hiện việc này bằng courses.courseWork.studentSubmissions.modifyAttachments, như trong mẫu sau:

Java

classroom/snippets/src/main/java/ModifyAttachmentsStudentSubmission.java
StudentSubmission studentSubmission = null;
try {
  // Create ModifyAttachmentRequest object that includes a new attachment with a link.
  Link link = new Link().setUrl("https://en.wikipedia.org/wiki/Irrational_number");
  Attachment attachment = new Attachment().setLink(link);
  ModifyAttachmentsRequest modifyAttachmentsRequest =
      new ModifyAttachmentsRequest().setAddAttachments(Arrays.asList(attachment));

  // The modified studentSubmission object is returned with the new attachment added to it.
  studentSubmission =
      service
          .courses()
          .courseWork()
          .studentSubmissions()
          .modifyAttachments(courseId, courseWorkId, id, modifyAttachmentsRequest)
          .execute();

  /* Prints the modified student submission. */
  System.out.printf(
      "Modified student submission attachments: '%s'.\n",
      studentSubmission.getAssignmentSubmission().getAttachments());
} catch (GoogleJsonResponseException e) {
  // TODO (developer) - handle error appropriately
  GoogleJsonError error = e.getDetails();
  if (error.getCode() == 404) {
    System.out.printf(
        "The courseId (%s), courseWorkId (%s), or studentSubmissionId (%s) does "
            + "not exist.\n",
        courseId, courseWorkId, id);
  } else {
    throw e;
  }
} catch (Exception e) {
  throw e;
}
return studentSubmission;

Python

lớp học/snippets/classroom_add_attachment.py
def classroom_add_attachment(course_id, coursework_id, submission_id):
  """
  Adds attachment to existing course with specific course_id.
  Load pre-authorized user credentials from the environment.
  TODO(developer) - See https://developers.google.com/identity
  for guides on implementing OAuth2 for the application.
  """
  creds, _ = google.auth.default()
  # pylint: disable=maybe-no-member
  request = {
      "addAttachments": [
          {"link": {"url": "http://example.com/quiz-results"}},
          {"link": {"url": "http://example.com/quiz-reading"}},
      ]
  }

  try:
    service = build("classroom", "v1", credentials=creds)
    while True:
      coursework = service.courses().courseWork()
      coursework.studentSubmissions().modifyAttachments(
          courseId=course_id,
          courseWorkId=coursework_id,
          id=submission_id,
          body=request,
      ).execute()

  except HttpError as error:
    print(f"An error occurred: {error}")


if __name__ == "__main__":
  # Put the course_id, coursework_id and submission_id of course in which
  # attachment needs to be added.
  classroom_add_attachment("course_id", "coursework_id", "me")

Tệp đính kèm đường liên kết được xác định bằng URL đích; Lớp học sẽ tự động tìm nạp tiêu đề và hình thu nhỏ. Bạn có thể tìm hiểu về các tài liệu khác ở trang tham khảo tương ứng.

StudentSubmission chỉ có thể do giáo viên khoá học hoặc học viên sở hữu lớp đó sửa đổi. Bạn chỉ có thể đính kèm Materials nếu CourseWorkType trong bài tập mà học viên nộp là ASSIGNMENT.

Phạm vi bắt buộc sẽ tuỳ thuộc vào vai trò của người dùng yêu cầu trong khoá học. Hãy dùng phạm vi sau nếu người dùng là giáo viên:

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

Hãy sử dụng phạm vi sau nếu người dùng là học viên:

  • https://www.googleapis.com/auth/classroom.coursework.me

Quản lý trạng thái phản hồi của học viên

Bài làm của học viên có thể bị huỷ, nộp hoặc trả lại. Trường trạng thái trong StudentSubmission cho biết trạng thái hiện tại. Để thay đổi trạng thái, hãy gọi một trong các phương thức sau:

Tất cả các phương thức này đều lấy một phần nội dung trống. Ví dụ:

Java

classroom/snippets/src/main/java/ReturnStudentSubmission.java
try {
  service
      .courses()
      .courseWork()
      .studentSubmissions()
      .classroomReturn(courseId, courseWorkId, id, null)
      .execute();
} catch (GoogleJsonResponseException e) {
  // TODO (developer) - handle error appropriately
  GoogleJsonError error = e.getDetails();
  if (error.getCode() == 404) {
    System.out.printf(
        "The courseId (%s), courseWorkId (%s), or studentSubmissionId (%s) does "
            + "not exist.\n",
        courseId, courseWorkId, id);
  } else {
    throw e;
  }
} catch (Exception e) {
  throw e;
}

Python

service.courses().courseWork().studentSubmission().turnIn(
    courseId=<course ID or alias>,
    courseWorkId=<courseWork ID>,
    id=<studentSubmission ID>,
    body={}).execute()

Chỉ học viên sở hữu StudentSubmission mới có thể nộp hoặc lấy lại bài tập này. Chúng tôi chỉ có thể thu hồi một bài tập đã nộp. Giáo viên của khoá học chỉ có thể trả về một StudentSubmission ở trạng thái đã bật.

Chấm điểm câu trả lời của học viên

Tài nguyên StudentSubmission có hai trường để lưu trữ điểm: assignedGrade là điểm được báo cáo cho học viên và draftGrade, là điểm dự kiến chỉ hiển thị với giáo viên. Các trường này được cập nhật bằng cách sử dụng courses.courseWork.studentSubmissions.patch với một mặt nạ trường chứa các trường thích hợp, như trong mẫu sau.

Java

classroom/snippets/src/main/java/PatchStudentSubmission.java
StudentSubmission studentSubmission = null;
try {
  // Updating the draftGrade and assignedGrade fields for the specific student submission.
  StudentSubmission content =
      service
          .courses()
          .courseWork()
          .studentSubmissions()
          .get(courseId, courseWorkId, id)
          .execute();
  content.setAssignedGrade(90.00);
  content.setDraftGrade(80.00);

  // The updated studentSubmission object is returned with the new draftGrade and assignedGrade.
  studentSubmission =
      service
          .courses()
          .courseWork()
          .studentSubmissions()
          .patch(courseId, courseWorkId, id, content)
          .set("updateMask", "draftGrade,assignedGrade")
          .execute();

  /* Prints the updated student submission. */
  System.out.printf(
      "Updated student submission draft grade (%s) and assigned grade (%s).\n",
      studentSubmission.getDraftGrade(), studentSubmission.getAssignedGrade());
} catch (GoogleJsonResponseException e) {
  // TODO (developer) - handle error appropriately
  GoogleJsonError error = e.getDetails();
  if (error.getCode() == 404) {
    System.out.printf(
        "The courseId (%s), courseWorkId (%s), or studentSubmissionId (%s) does "
            + "not exist.\n",
        courseId, courseWorkId, id);
  } else {
    throw e;
  }
} catch (Exception e) {
  throw e;
}
return studentSubmission;

Python

studentSubmission = {
  'assignedGrade': 99,
  'draftGrade': 80
}
service.courses().courseWork().studentSubmissions().patch(
    courseId=<course ID or alias>,
    courseWorkId=<courseWork ID>,
    id=<studentSubmission ID>,
    updateMask='assignedGrade,draftGrade',
    body=studentSubmission).execute()

Khi sử dụng giao diện người dùng Lớp học, giáo viên không thể giao điểm cho đến khi lưu điểm không chính thức trước tiên. Sau đó, bạn có thể trả lại điểm cho học viên. Các ứng dụng cần mô phỏng hành vi này. Ứng dụng của bạn có thể chấm điểm bài tập của học viên theo một trong hai cách:

  • Chỉ gán draftGrade. Tính năng này rất hữu ích, chẳng hạn như cho phép giáo viên xem điểm theo cách thủ công trước khi tổng kết. Học viên không thể xem điểm không chính thức.

  • Giao cả draftGradeassignedGrade để chấm điểm đầy đủ cho một bài tập.

Liệt kê điểm đã chỉ định

Bạn có thể liệt kê tất cả điểm cho một mục cụ thể trong bài tập bằng cách khám phá đối tượng phản hồi của phương thức courses.courseWork.studentSubmissions.list:

Java

classroom/snippets/src/main/java/ListStudentSubmissions.java
  ListStudentSubmissionsResponse response =
      service
          .courses()
          .courseWork()
          .studentSubmissions()
          .list(courseId, courseWorkId)
          .setPageToken(pageToken)
          .execute();

  /* Ensure that the response is not null before retrieving data from it to avoid errors. */
  if (response.getStudentSubmissions() != null) {
    studentSubmissions.addAll(response.getStudentSubmissions());
    pageToken = response.getNextPageToken();
  }
} while (pageToken != null);

if (studentSubmissions.isEmpty()) {
  System.out.println("No student submissions found.");
} else {
  for (StudentSubmission submission : studentSubmissions) {
    System.out.printf(
        "User ID %s, Assigned grade: %s\n",
        submission.getUserId(), submission.getAssignedGrade());
  }
}

Python

response = coursework.studentSubmissions().list(
    courseId=course_id,
    courseWorkId=coursework_id,
    pageSize=10).execute()
submissions.extend(response.get('studentSubmissions', []))

if not submissions:
    print('No student submissions found.')

print('Student Submissions:')
for submission in submissions:
    print(f"Submitted at:"
          f"{(submission.get('userId'), submission.get('assignedGrade'))}")