외부 첨부파일 및 제출

이 가이드는 클래스룸 부가기능 둘러보기 시리즈의 일곱 번째 둘러보기입니다.

이 둘러보기에서는 웹 애플리케이션에 Google 클래스룸 외부에서 부가기능 첨부파일을 만드는 동작을 추가합니다. 이 동작을 사용하면 사용자가 기존 제품 또는 웹사이트에서 부가기능 첨부파일을 만들 수 있습니다. 또한 흐름을 변경하지 않고 부가기능에서 제공하는 개선된 사용자 환경으로 기존 트래픽을 전달하기 때문에 CourseWork 통합에 큰 도움이 됩니다. 제안된 절차는 클래스룸 외부에서 첨부파일 만들기 가이드 페이지에 나와 있습니다.

또한 부가기능에 동작을 추가하여 부가기능 연결을 사용하여 프로그래매틱 방식으로 할당을 수정합니다. 할당을 만든 사용자와 관계없이 부가기능 첨부파일이 있는 모든 할당을 수정할 수 있습니다. 이는 특히 학생이 활동을 완료한 후 과제를 제출하여 할당된 작업이 완료되었고 학생의 과제물을 검토할 준비가 되었음을 알리는 데 유용합니다.

콘텐츠 유형 또는 활동 유형 첨부파일을 지원하는 부가기능의 최종 버전을 확장합니다. 이 가이드에서는 콘텐츠 유형 첨부파일을 사용합니다.

할당 관리 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 SDK, OAuth 동의 화면, 서버 코드에서 범위 목록에 추가합니다.

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",
  ]

클래스룸에서 과제 만들기

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>

CourseWork 관련 경로를 처리할 새 Python 모듈 파일을 만듭니다. 제공된 예에서 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. Google 클래스룸에서 첨부파일 없이 courseWork 과제를 만들도록 API 요청을 보냅니다.
  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 클래스룸 스트림 항목에 액세스하거나 이를 수정, 제출, 회수 또는 반환할 수 있습니다. 스트림 항목은 Announcement, CourseWork 할당 또는 CourseWorkMaterial입니다.

이를 보여주기 위해 지정된 스트림 항목을 수정하는 경로를 추가합니다. API를 사용하여 내가 만든 Google 클래스룸 UI를 통해 교사가 만든 스트림 항목에 액세스하고 수정할 수 있는지 확인하려면 이 메서드를 사용하세요.

이 둘러보기에서 처음 수정한 웹페이지에 링크 또는 버튼을 하나 더 추가합니다. 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 for Education Teaching & Learning 또는 Plus 라이선스가 없는 교사 사용자로 로그인합니다. 테스트 도메인의 관리 콘솔에서 사용자의 라이선스 상태를 전환할 수 있습니다.CourseWork Assignment(CourseWork 과제 만들기) 버튼을 클릭한 다음 Google Classroom UI를 열고 Link Material 첨부파일이 포함된 과제가 생성되었는지 확인합니다. 첨부파일에는 링크된 웹페이지의 제목과 URL이 표시되어야 합니다.

부가기능 첨부파일 만들기 테스트

색인 페이지로 돌아가서 Google Workspace for Education Teaching and Learning 또는 Plus 라이선스가 있는 교사 사용자로 로그인합니다. CourseWork 과제 만들기 버튼을 클릭한 다음 Google 클래스룸 UI를 열고 부가기능 첨부파일이 포함된 과제가 생성되었는지 확인합니다. 첨부파일에는 부가기능 애플리케이션의 이름과 코드에 지정된 제목이 표시되어야 합니다.

할당 수정 테스트

색인 페이지로 돌아가서 Teaching and Learning 또는 Plus 라이선스가 있는 교사 사용자로 로그인했는지 확인합니다. CourseWork 과제 수정 버튼을 클릭한 다음 Google 클래스룸 UI로 돌아가서 과제 제목이 변경되었는지 확인합니다.

수고하셨습니다 둘러보기 시리즈를 완료했습니다.