외부 첨부파일 및 제출

클래스룸 부가기능의 일곱 번째 둘러보기입니다. 오신 것을 환영합니다

이 둘러보기에서는 웹 애플리케이션에 부가기능을 만드는 동작을 추가합니다. 첨부파일을 업로드할 수 있습니다. 이 동작을 사용하여 사용자가 기존 제품이나 웹사이트에서 부가기능 첨부파일을 만들 수 있습니다. 이것은 CourseWork 통합의 또 다른 추가 기능으로, 기존 SDK를 직접 향상된 사용자 환경으로 유입되는 트래픽을 변경하지 않고도 파악할 수 있습니다. 권장되는 절차는 첨부파일 만들기 클래스룸 가이드 페이지 외부

부가기능으로 과제를 수정하는 동작을 부가기능에 추가할 수도 있습니다. 프로그래매틱 방식으로 첨부 파일을 업로드할 수도 있습니다. 다음 중 하나가 포함된 모든 과제를 수정할 수 있습니다. 모든 부가기능 첨부파일을 공유할 수 있습니다. 이것은 학생이 마지막 학사 과정을 완료한 후 과제를 제출할 때 특히 이를 통해 할당된 작업이 완료되었다는 신호를 보내며 학생 과제물을 검토할 준비가 되었습니다.

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

할당 관리 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 할당을 만들거나 수정하는 데 사용됩니다. 목록에 이 범위 추가 Google 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입니다. 다음을 추가합니다. 3개 경로 나중에 일부 콘텐츠를 채울 것입니다

# /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 애널리틱스 계정을 만들려면 사용자가 충족해야 하는 몇 가지 기본 요건이 있습니다. 사용자를 대신하여 부가기능 첨부파일을 전송할 수 있습니다 편의를 위해 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. courseWork 할당을 만드는 API 요청 보내기 첨부파일이 없는 Google 클래스룸
  2. 새로 만든 할당의 id를 추출합니다.
  3. CourseWork AddOnAttachment를 만듭니다.
  4. 새로 생성된 할 수 있습니다.

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

사용자가 부가기능 첨부파일을 만들 수 없는 경우 링크를 만듭니다. Material을 대신 다음과 같이 해 보세요.

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

부가기능 테스트

편의를 위해 제공된 예에서는 하드 코딩된 과정과 사용할 수 있습니다. 다음과 같이 요청하여 이러한 식별자를 가져올 수 있습니다. coursesgetlist 메서드에 대한 교사 사용자 인증 정보 및 courseWork 리소스 또한 과제 courseWork

서버를 실행한 다음 색인 페이지로 이동하여 교사 사용자로 로그인합니다. Google Workspace for Education을 사용하지 않는 Learning 또는 Plus 라이선스. 전환하세요. 사용자의 라이선스 상태를 참고하세요. 관리 콘솔에서 CourseWork 과제 만들기를 클릭합니다. 버튼을 클릭한 다음 Google 클래스룸 UI를 열고 링크 Material 첨부파일을 만들었습니다. 첨부파일에는 URL을 입력합니다.

부가기능 첨부파일 생성 테스트

색인 페이지로 돌아가서 Google Workspace for Education Teaching를 사용하는 교사 사용자로 로그인합니다. &amp; Learning 또는 Plus 라이선스. Create a CourseWork 과제 만들기를 클릭합니다. 버튼을 클릭한 다음 Google 클래스룸 UI를 열고 부가기능 첨부파일이 생성되었습니다. 첨부파일에는 코드에 지정된 제목이 있을 수 있습니다.

테스트 할당 수정

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

축하합니다. 둘러보기 시리즈를 완료했습니다.