コンテンツ タイプの添付ファイル

これは Classroom アドオンに関する 4 番目のチュートリアルです 説明します。

このチュートリアルでは、Google Classroom API を操作して、 できます。ユーザーが添付ファイルの内容を閲覧するためのルートを提供します。「 クラスでのユーザーのロールによって異なります。このチュートリアルでは、以下について説明します。 コンテンツ タイプの添付ファイル: 生徒からの提出を必要としません。

このチュートリアルでは、次のことを行います。

  • 次のアドオン クエリ パラメータを取得して使用します。
    • addOnToken: 添付ファイルの検出に渡される認証トークン 表示。
    • itemId: CourseWork、CourseWorkMaterial または CourseWorkMaterial の固有識別子。 アドオンの添付ファイルを受け取るお知らせ。
    • itemType: 「courseWork」、「courseWorkMaterials」のいずれかまたは 「発表」のような内容にします。
    • courseId: Google Classroom コースの一意の識別子 割り当てを作成する場所です。
    • attachmentId: Google Classroom によってクラスに割り当てられる一意の識別子 作成後のアドオンの添付ファイルが含まれます。
  • コンテンツ タイプの添付ファイル用の永続ストレージを実装します。
  • 添付ファイルを作成するルートや、教師に表示される画面を提供するルートを提供する 生徒に表示される iFrame
  • Google Classroom アドオン API に次のリクエストを発行します。
    • 新しい添付ファイルを作成します。
    • アドオン コンテキストを取得します。このコンテキストにより、ログインしているユーザーが 役立ちます。

完了したら、 教師としてログインすると、Google Classroom の UI を使用できます。教師と生徒 そのクラスはコンテンツを閲覧することもできます。

Classroom API を有効にする

このステップから Classroom API を呼び出します。API は 有効にしておく必要があります。ナビ開始 Google Classroom API のライブラリ エントリに移動し、[有効にする] を選択します。

Attachment Discovery View クエリ パラメータを処理する

すでに説明したように、Google Classroom は iframe で添付ファイルの検出ビューを読み込む:

  • courseId: 現在の Classroom コースの ID。
  • itemId: CourseWork、CourseWorkMaterial または CourseWorkMaterial の固有識別子。 アドオンの添付ファイルを受け取るお知らせ。
  • itemType: 「courseWork」、「courseWorkMaterials」のいずれか「お知らせ」などです。
  • addOnToken: 特定のものを承認するために使用されるトークン Classroom アドオンのアクション。
  • login_hint: 現在のユーザーの Google ID。

このチュートリアルでは、courseIditemIditemTypeaddOnToken について説明します。 Classroom API の呼び出しを発行する際に、これらを保持して渡します。

前のチュートリアルの手順と同様に、渡されたクエリ パラメータ値を 説明します。この確認は添付ファイルの検出ビューが これが Classroom で クエリ パラメータを渡します。

Python

Attachment のルートが含まれている Flask サーバー ファイルに移動します。 ファインド ビュー(attachment-discovery-routes.py 例を参照)アドオンのランディング ルートの先頭 (この例では /classroom-addon)、 courseIditemIditemTypeaddOnToken クエリ パラメータ。

# Retrieve the itemId, courseId, and addOnToken query parameters.
if flask.request.args.get("itemId"):
    flask.session["itemId"] = flask.request.args.get("itemId")
if flask.request.args.get("itemType"):
    flask.session["itemType"] = flask.request.args.get("itemType")
if flask.request.args.get("courseId"):
    flask.session["courseId"] = flask.request.args.get("courseId")
if flask.request.args.get("addOnToken"):
    flask.session["addOnToken"] = flask.request.args.get("addOnToken")

これらの値が存在する場合にのみセッションに書き込みます。それは ユーザーが偶発的に添付ファイルの検出ビューに戻った場合に再び渡されます。 後で iframe を閉じないでください。

コンテンツ タイプの添付ファイル用の永続ストレージを追加する

作成した添付ファイルのローカル レコードが必要です。これにより によって提供される ID を使用して教師が選択したコンテンツ Classroom。

Attachment のデータベース スキーマを設定します。ここで紹介した例は 添付されていますAttachment には、 次のような属性があります。

  • attachment_id: アタッチメントの一意の識別子。割り当て元 メッセージの作成時にレスポンスで返される 添付します。
  • image_filename: 表示する画像のローカル ファイル名。
  • image_caption: 画像とともに表示するキャプション。
で確認できます。

Python

前のステップの SQLite と flask_sqlalchemy の実装を拡張します。

ユーザー テーブル(models.py)を定義したファイルに移動します。 をご覧ください)。一番下に以下を追加します。 User クラスの下にあります。

class Attachment(db.Model):
    # The attachmentId is the unique identifier for the attachment.
    attachment_id = db.Column(db.String(120), primary_key=True)

    # The image filename to store.
    image_filename = db.Column(db.String(120))

    # The image caption to store.
    image_caption = db.Column(db.String(120))

新しい Attachment クラスを、添付ファイルを含むサーバー ファイルにインポートします。 ルートの処理。

新しいルートを設定する

このチュートリアルの手順では、まずアプリケーションに新しいページをいくつか設定します。 これにより、ユーザーはアドオンを通じてコンテンツを作成、表示できます。

アタッチメント作成ルートを追加する

教師がコンテンツを選択し、添付ファイルの作成を発行するためのページが必要です できます。コンテンツ オプションを表示するための /attachment-options ルートを実装する 選択することもできます。また、コンテンツの選択や管理のために作成したテンプレートも 作成確認ページが開きますこれらの例にはテンプレートのほか 受け取ったリクエストとレスポンスを表示することも Classroom API。

既存の添付ファイルの検出ビューを変更することもできます。 コンテンツ オプションを表示するため、新しいランディング ページを作成せずに、 /attachment-options ページ。次の目的で新しいページを作成することをおすすめします この演習を行い、2 つ目の URL に実装された SSO の動作を維持します。 チュートリアルの手順に沿って進めてください。これらは アドオンのビルドとテストに役立ちます。

用意された用意された字幕付き画像の中から教師は 例です。有名なランドマークの画像が 4 枚用意されており、それぞれに ファイル名から導き出されます

Python

上記の例では、webapp/attachment_routes.py ファイル内にあります。

@app.route("/attachment-options", methods=["GET", "POST"])
def attachment_options():
    """
    Render the attachment options page from the "attachment-options.html"
    template.

    This page displays a grid of images that the user can select using
    checkboxes.
    """

    # A list of the filenames in the static/images directory.
    image_filenames = os.listdir(os.path.join(app.static_folder, "images"))

    # The image_list_form_builder method creates a form that displays a grid
    # of images, checkboxes, and captions with a Submit button. All images
    # passed in image_filenames will be shown, and the captions will be the
    # title-cased filenames.

    # The form must be built dynamically due to limitations in WTForms. The
    # image_list_form_builder method therefore also returns a list of
    # attribute names in the form, which will be used by the HTML template
    # to properly render the form.
    form, var_names = image_list_form_builder(image_filenames)

    # If the form was submitted, validate the input and create the attachments.
    if form.validate_on_submit():

        # Build a dictionary that maps image filenames to captions.
        # There will be one dictionary entry per selected item in the form.
        filename_caption_pairs = construct_filename_caption_dictionary_list(
            form)

        # Check that the user selected at least one image, then proceed to
        # make requests to the Classroom API.
        if len(filename_caption_pairs) > 0:
            return create_attachments(filename_caption_pairs)
        else:
            return flask.render_template(
                "create-attachment.html",
                message="You didn't select any images.",
                form=form,
                var_names=var_names)

    return flask.render_template(
        "attachment-options.html",
        message=("You've reached the attachment options page. "
                "Select one or more images and click 'Create Attachment'."),
        form=form,
        var_names=var_names,
    )

[Create Attachments] 画面が表示されます。次のようなページが表示されます。

Python のコンテンツ選択ビューの例

教師は複数の画像を選択できます。画像ごとに 1 つの添付ファイルを作成する 教師が create_attachments メソッドで選択したラベル値。

添付ファイルの作成リクエストを発行する

添付したいコンテンツがわかったので Classroom API にリクエストを送信し、 割り当てます。メッセージの受信後、アタッチメントの詳細をデータベースに保存する Classroom API からのレスポンス。

まず、Classroom サービスのインスタンスを取得します。

Python

上記の例では、webapp/attachment_routes.py ファイル内にあります。

def create_attachments(filename_caption_pairs):
    """
    Create attachments and show an acknowledgement page.

    Args:
        filename_caption_pairs: A dictionary that maps image filenames to
            captions.
    """
    # Get the Google Classroom service.
    classroom_service = googleapiclient.discovery.build(
        serviceName="classroom",
        version="v1",
        credentials=credentials)

courses.courseWork.addOnAttachmentsCREATE リクエストを発行します。 接続できます教師によって選択された画像ごとに、まず AddOnAttachment オブジェクト:

Python

上記の例では、これは create_attachments の続きです。 メソッドを呼び出します。

# Create a new attachment for each image that was selected.
attachment_count = 0
for key, value in filename_caption_pairs.items():
    attachment_count += 1

    # Create a dictionary with values for the AddOnAttachment object fields.
    attachment = {
        # Specifies the route for a teacher user.
        "teacherViewUri": {
            "uri":
                flask.url_for(
                    "load_content_attachment", _scheme='https', _external=True),
        },
        # Specifies the route for a student user.
        "studentViewUri": {
            "uri":
                flask.url_for(
                    "load_content_attachment", _scheme='https', _external=True)
        },
        # The title of the attachment.
        "title": f"Attachment {attachment_count}",
    }

少なくとも teacherViewUristudentViewUrititle の各フィールドは、 表示されます。teacherViewUristudentViewUri は、添付ファイルが開かれたときに読み込まれる URL を表します。 選択できます。

リクエストの本文で AddOnAttachment オブジェクトを適切な addOnAttachments エンドポイント。courseIditemIditemTypeaddOnToken 識別子を各リクエストに付加します。

Python

上記の例では、これは create_attachments の続きです。 メソッドを呼び出します。

# Use the itemType to determine which stream item type the teacher created
match flask.session["itemType"]:
    case "announcements":
        parent = classroom_service.courses().announcements()
    case "courseWorkMaterials":
        parent = classroom_service.courses().courseWorkMaterials()
    case _:
        parent = classroom_service.courses().courseWork()

# Issue a request to create the attachment.
resp = parent.addOnAttachments().create(
    courseId=flask.session["courseId"],
    itemId=flask.session["itemId"],
    addOnToken=flask.session["addOnToken"],
    body=attachment).execute()

後で使用できるように、このアタッチメントのエントリをローカル データベースに作成します。 正しいコンテンツを読み込みます。Classroom から一意の id 値が返される 作成リクエストに対するレスポンスで識別されるため、これを データベースですまた、Classroom は attachmentId 教師ビューと生徒のビューを開く際のクエリ パラメータ:

Python

上記の例では、これは create_attachments の続きです。 メソッドを呼び出します。

# Store the value by id.
new_attachment = Attachment(
    # The new attachment's unique ID, returned in the CREATE response.
    attachment_id=resp.get("id"),
    image_filename=key,
    image_caption=value)
db.session.add(new_attachment)
db.session.commit()

この時点で、ユーザーに確認ページにリダイレクトし、メッセージを確認することを検討します。 添付ファイルが正常に作成されたことを確認します。

アドオンからの添付ファイルを許可する

ここで、許可されたアタッチメントに適切なアドレスを追加します。 Google Workspace Marketplace SDK のアプリの構成の [URI Prefixes] フィールド できます。アドオンは、いずれかの URI プレフィックスからのみ添付ファイルを作成できます ご覧くださいこれは、問題が発生する可能性を減らすためのセキュリティ対策です。 軽減されます。

最も簡単な方法は、このフィールドにトップレベル ドメインを指定することです。 (例: https://example.com)。https://localhost:<your port number>/ さんは次の行動をとるでしょう ローカルマシンをウェブサーバーとして使用している場合に動作します。

教師ビューと生徒ビューのルートを追加する

Google Classroom アドオンを読み込むための iframe は 4 つあります。 Attachment Discovery View iframe を配信するルートのみが構築されているため、 遠くはなれません。次に、教師と生徒用のビューの iframe にも配信するルートを追加します。

生徒のプレビューを表示するには、Teacher View iframe が必要です。 ただし、必要に応じて追加情報や編集を加えたり、 説明します。

生徒用ビューは、各生徒が開いたときに表示されるページです。 作成します。

この演習では、単一の /load-content-attachment を作成します。 教師ビューと生徒ビューの両方を提供します。Classroom API を使用する ユーザーが教師か生徒かを判別するためのメソッドです。 表示されます。

Python

上記の例では、webapp/attachment_routes.py ファイル内にあります。

@app.route("/load-content-attachment")
def load_content_attachment():
    """
    Load the attachment for the user's role."""

    # Since this is a landing page for the Teacher and Student View iframes, we
    # need to preserve the incoming query parameters.
    if flask.request.args.get("itemId"):
        flask.session["itemId"] = flask.request.args.get("itemId")
    if flask.request.args.get("itemType"):
        flask.session["itemType"] = flask.request.args.get("itemType")
    if flask.request.args.get("courseId"):
        flask.session["courseId"] = flask.request.args.get("courseId")
    if flask.request.args.get("attachmentId"):
        flask.session["attachmentId"] = flask.request.args.get("attachmentId")

この時点でユーザーの認証も行う必要があることに留意してください。マイページ ここで login_hint クエリ パラメータも処理し、ユーザーを 承認フローを実行します。ログイン ガイダンスの詳細をご覧ください。 をご覧ください。

次に、アイテムに一致する getAddOnContext エンドポイントにリクエストを送信します。 あります。

Python

こちらの例では、 load_content_attachment メソッドを使用します。

# Create an instance of the Classroom service.
classroom_service = googleapiclient.discovery.build(
    serviceName="classroom"
    version="v1",
    credentials=credentials)

# Use the itemType to determine which stream item type the teacher created
match flask.session["itemType"]:
    case "announcements":
        parent = classroom_service.courses().announcements()
    case "courseWorkMaterials":
        parent = classroom_service.courses().courseWorkMaterials()
    case _:
        parent = classroom_service.courses().courseWork()

addon_context_response = parent.getAddOnContext(
    courseId=flask.session["courseId"],
    itemId=flask.session["itemId"]).execute()

このメソッドは、クラス内での現在のユーザーの役割に関する情報を返します。 ユーザーの役割に応じて、ユーザーに表示されるビューを変更します。 studentContext フィールドまたは teacherContext フィールドには、レスポンスで値が入力されます。 オブジェクト。これらを調べて、お客様への対応方法を判断します。

いずれの場合も、attachmentId クエリ パラメータ値を使用して、 データベースから取得します。このクエリ パラメータは、 教師用ビューまたは生徒用ビューの URI を開きます。

Python

こちらの例では、 load_content_attachment メソッドを使用します。

# Determine which view we are in by testing the returned context type.
user_context = "student" if addon_context_response.get(
    "studentContext") else "teacher"

# Look up the attachment in the database.
attachment = Attachment.query.get(flask.session["attachmentId"])

# Set the text for the next page depending on the user's role.
message_str = f"I see that you're a {user_context}! "
message_str += (
    f"I've loaded the attachment with ID {attachment.attachment_id}. "
    if user_context == "teacher" else
    "Please enjoy this image of a famous landmark!")

# Show the content with the customized message text.
return flask.render_template(
    "show-content-attachment.html",
    message=message_str,
    image_filename=attachment.image_filename,
    image_caption=attachment.image_caption,
    responses=response_strings)

アドオンをテストする

アタッチメントの作成をテストする手順は次のとおりです。

  • [Google Classroom] に 教師テストユーザー。
  • [授業] タブに移動し、新しい課題を作成します。
  • テキスト領域の下にある [アドオン] ボタンをクリックし、アドオンを選択します。 iframe が開き、アドオンによって、指定した添付ファイルの設定 URI が読み込まれます。 Google Workspace Marketplace SDK の [アプリの構成] ページで指定されます。
  • 課題に添付するコンテンツを選択します。
  • 添付ファイルの作成フローが完了したら、iframe を閉じます。

Google の課題作成 UI に添付ファイル カードが表示されます。 Google Classroomカードをクリックして Teacher View iframe を開き、確定する 正しい添付ファイルが表示されることを確認します。[Assign] ボタンをクリックします。

生徒の学習環境をテストする手順は次のとおりです。

  • 次に、同じ組織部門で学割プランのテストユーザーとして Classroom にログインします。 教師用テストユーザーとしてアクセスします。
  • [授業] タブでテスト用の課題を見つけます。
  • 課題を開き、添付ファイル カードをクリックして生徒用のビューを開く 使用できます。

生徒に正しい添付ファイルが表示されていることを確認します。

これで、次の手順「作成 アクティビティ タイプの添付ファイルをご覧ください。