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 trả lời 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 loại sau đây, được gọi là CourseWorkType cho API: Bài tập, 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 của CourseWork, biểu thị một Bài tập hoặc Câu hỏi đã được giao cho học sinh 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ư khoá học ngày hoặc điểm tối đa.

Ngoài tài nguyên trê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 mô tả chi tiết hơn.

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 và cố gắng tạo bài tập trong khóa học thay mặt cho học viên sẽ dẫn đến kết quả trong lỗi PERMISSION_DENIED 403. 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 họ khô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, trong đoạn 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

classroom/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ả chứa một giá trị nhận dạng do máy chủ chỉ định mà có thể dùng để tham chiếu quyền chỉ định trong các yêu cầu API khác.

Cách đưa tài liệu được liên kết vào một bài tập được tạo thông qua API Lớp học: sử dụng Tài nguyên đường liên kết, trong đó 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ác tài liệu này có thể kèm theo tài nguyên DriveFile hoặc Tài nguyên YouTubeVideo trong một .

Để chỉ định ngày đến hạn, hãy đặt trường dueDatedueTime thành giờ UTC tương ứng. Ngày đến hạn phải là 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 của quản trị viên miền. Để truy xuất một bài tập hoặc câu hỏi, hãy sử dụng dự kiến củaKhoá học.courseWork.get. Để truy xuất tất cả bài tập hoặc câu hỏi (có thể khớp với một số tiêu chí), hãy sử dụng courses.courseWork.list.

Phạm vi bắt buộc phụ thuộc vào vai trò của người dùng đưa ra yêu cầu trong khóa 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 tuỳ chọn sau phạm vi:

  • 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 một bài tập hoặc câu hỏi không có nghĩa là quyền truy cập tài liệu hoặc siêu dữ liệu tài liệu. Trong thực tế, điều này có nghĩa là quản trị viên có thể không thấy tiêu đề 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 người dùng tệp, hãy xem toàn bộ miền uỷ quyền của chúng tôi.

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

StudentSubmission tài nguyên biểu thị bài tập đã hoàn thành và điểm của một học viên trong một bài tập hoặc . StudentSubmission tài nguyên được tạo ngầm cho mỗi học sinh khi có câu hỏi hoặc bài tập sẽ được tạo.

Các phần sau đây giải thích những thao tác thường dùng để quản lý câu trả lời 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 chính mình, giáo viên có thể truy xuất bài tập đã nộp cho tất cả học viên trong khoá học của họ, đồng thời quản trị viên miền có thể truy xuất tất cả bài nộp cho tất cả học viên trong miền của họ. Mỗi bài học viên nộp là gán một giá trị nhận dạng; nếu bạn biết mã nhận dạng này, hãy sử dụng courses.courseWork.studentSubmissions.get để truy xuất dữ liệu đó.

Sử dụng phương thức courses.courseWork.studentSubmissions.list để tải Những tài nguyên StudentSubmission phù hợp với một số tiêu chí, như được hiển thị 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

classroom/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 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 sinh được xác định bằng mã nhận dạng duy nhất hoặc địa chỉ email của người dùng, như 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 bằng cách viết tắt "me".

Bạn cũng có thể nhận bài tập mà học viên đã nộp cho tất cả bài tập trong một khóa học. Để thực hiện việc này, hãy sử dụng giá trị cố định "-" dưới dạng courseWorkId, như minh hoạ 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 tuỳ thuộc vào vai trò của người dùng đưa ra yêu cầu trong khóa học. Sử dụng phạm vi sau nếu người dùng là giáo viên hoặc miền quản trị viên:

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

Hãy dùng phạm vi sau đây 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 học viên đã nộp không có nghĩa là quyền truy cập tệp đính kèm hoặc siêu dữ liệu tệp đính kèm. Trong thực tế, đây là có nghĩa là quản trị viên có thể không thấy tiêu đề của 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 tập học viên nộp bằng cách đính kèm một tệp Link, DriveFile hoặc tài nguyên YouTubeVideo. Việc này được thực hiện bằng courses.courseWork.studentSubmissions.modifyAttachments, như minh hoạ 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

classroom/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 theo 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 tại trang tham khảo tương ứng.

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

Phạm vi bắt buộc phụ thuộc vào vai trò của người dùng đưa ra yêu cầu trong khóa học. Hãy sử 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 dùng phạm vi sau đây 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 trả lời của học viên

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

Tất cả các phương thức này đều lấy 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 đó. Chỉ có thể lấy lại bài đã nộp. Giáo viên trong khoá học chỉ có thể trả lại StudentSubmission đang ở trạng thái đã nộp.

Câu trả lời của học viên trong chương trình chấm điểm

Tài nguyên StudentSubmission có 2 trường để lưu trữ điểm: assignedGrade là điểm được báo cáo cho học sinh và draftGrade, đây là điểm dự kiến mà chỉ giáo viên mới nhìn thấy. Những trường này đã được cập nhật 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ư được thể hiện 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 chỉ có thể chấm điểm đã lưu điểm không chính thức. Sau đó, bạn có thể trả điểm đã giao 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ỉ chỉ định draftGrade. Ví dụ: điều này hữu ích để cho phép giáo viên kiểm tra điểm theo cách thủ công trước khi chấm dứt. Học viên không thể xem điểm không chính thức.

  • Chỉ định cả draftGradeassignedGrade để chấm điểm đầy đủ bài tập.

Liệt kê điểm đã giao

Bạn có thể liệt kê tất cả điểm trong một mục tài liệu môn học cụ thể 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'))}")