مدیریت نام مستعار دوره، مدیریت نام مستعار دوره

شما می‌توانید با استفاده از نام مستعار دوره، به دوره‌ها با نام دیگری ارجاع دهید. نام‌های مستعار دوره می‌توانند به عنوان نگاشتی بین شناسه‌های دوره Google Classroom و شناسه‌های دوره خارجی عمل کنند. به عنوان مثال، می‌توانید یک نام مستعار دوره را طوری تنظیم کنید که با شناسه دوره از یک سیستم اطلاعات دانشجویی (SIS) مطابقت داشته باشد.

نام مستعار دوره دو شکل دارد: دامنه-گستر و پروژه-گستر.

  • نام‌های مستعار در سطح دامنه از پیشوند d: استفاده می‌کنند و هر کسی که از Classroom API استفاده می‌کند می‌تواند آنها را ببیند. فضای نام دامنه برای ایجاد نام‌های مستعاری که همه کاربران نیاز به دسترسی به آنها دارند، اما مختص هیچ برنامه خاصی نیستند، مفید است. به عنوان مثال، فهرست‌های جایگزین برای یک دوره، مانند MATH 127 و COMSCI 127، باید در فضای نام دامنه ایجاد شوند. نام‌های مستعار در فضای نام دامنه فقط می‌توانند توسط مدیران دامنه ایجاد شوند، اما برای همه کاربران در یک دامنه قابل مشاهده هستند.

  • نام‌های مستعار در سطح پروژه از پیشوند p: استفاده می‌کنند و فقط توسط پروژه Google Cloud که آنها را ایجاد کرده است، قابل مشاهده و استفاده هستند. فضای نام پروژه توسعه‌دهنده برای مدیریت نام‌های مستعار خاص یک برنامه مفید است. به عنوان مثال، برنامه‌ای که از شناسه‌های جایگزین برای دوره‌ها استفاده می‌کند، می‌تواند نام‌های مستعاری ایجاد کند تا شناسه خود را به دوره‌های Classroom نگاشت کند. نام‌های مستعار ایجاد شده در این فضای نام به یک پروژه Google Cloud خاص گره خورده‌اند. هر کاربر یک برنامه می‌تواند نام‌های مستعار را در فضای نام برای پروژه توسعه‌دهنده آن برنامه ایجاد و مشاهده کند.

می‌توان از یک نام مستعار دوره به جای شناسه دوره Classroom برای هر نقطه پایانی API کلاس درس استفاده کرد. این بدان معناست که می‌توان از این نام مستعار برای خواندن و تغییر اطلاعات دوره‌ها و فهرست استفاده کرد.

استفاده از نام مستعار برای همگام‌سازی با سیستم‌های اطلاعات دانشجویی

شناسه داخلی SIS برای یک دوره می‌تواند به عنوان یک نام مستعار در سطح دامنه برای دوره ثبت شود. به این ترتیب، هر توسعه‌دهنده‌ای که با SIS و Classroom ادغام می‌شود، می‌تواند از شناسه SIS برای تعامل با داده‌های Classroom استفاده کند.

اگر دوره‌ای را از یک SIS ایجاد می‌کنید یا دوره‌ای را به SIS پیوند می‌دهید، توصیه می‌شود از شناسه دوره SIS به عنوان نام مستعار دوره استفاده شود. هنگام ایجاد یک دوره با استفاده از متد courses.create() ، می‌توانید نام مستعار را در فیلد id درخواست مشخص کنید. اگر نام مستعار از قبل وجود داشته باشد، ایجاد دوره با خطای 409 ALREADY_EXISTS ناموفق خواهد بود. این کار در صورت وجود مشکل در برنامه همگام‌سازی، از ایجاد دوره‌های تکراری جلوگیری می‌کند.

برای مثال، اگر فرض کنیم نام SIS school است و شناسه داخلی مورد استفاده SIS برای یک دوره خاص math_101 است، می‌توانید یک نام مستعار به صورت d:school_math_101 ایجاد کنید.

افزودن نام مستعار برای یک دوره جدید

برای افزودن نام مستعار برای یک دوره جدید، هنگام ایجاد درخواست courses.create() course.id به یک نام مستعار تنظیم کنید.

اسکریپت برنامه‌ها

class/snippets/createAlias.gs
/**
 * Creates Course with an alias specified
 */
function createAlias() {
  let course = {
    id: "p:bio_101",
    name: "10th Grade Biology",
    section: "Period 2",
    descriptionHeading: "Welcome to 10th Grade Biology",
    description:
      "We'll be learning about the structure of living creatures from a combination " +
      "of textbooks, guest lectures, and lab work. Expect to be excited!",
    room: "301",
    ownerId: "me",
    courseState: "PROVISIONED",
  };
  try {
    // Create the course using course details.
    course = Classroom.Courses.create(course);
    console.log("Course created: %s (%s)", course.name, course.id);
  } catch (err) {
    // TODO (developer) - Handle Courses.create() exception
    console.log(
      "Failed to create course %s with an error %s",
      course.name,
      err.message,
    );
  }
}

جاوا

کلاس/قطعه کد/src/main/java/CreateCourseWithAlias.java
Course course = null;

/* Create a new Course with the alias set as the id field. Project-wide aliases use a prefix
of "p:" and can only be seen and used by the application that created them. */
Course content =
    new Course()
        .setId("p:history_4_2022")
        .setName("9th Grade History")
        .setSection("Period 4")
        .setDescriptionHeading("Welcome to 9th Grade History.")
        .setOwnerId("me")
        .setCourseState("PROVISIONED");

try {
  course = service.courses().create(content).execute();
  // Prints the new created course id and name
  System.out.printf("Course created: %s (%s)\n", course.getName(), course.getId());
} catch (GoogleJsonResponseException e) {
  // TODO (developer) - handle error appropriately
  GoogleJsonError error = e.getDetails();
  if (error.getCode() == 409) {
    System.out.printf("The course alias already exists: %s.\n", content.getId());
  } else {
    throw e;
  }
} catch (Exception e) {
  throw e;
}
return course;

پایتون

کلاس/قطعه قطعه/کلاس_اضافه_نام مستعار_جدید.py
SCOPES = ["https://www.googleapis.com/auth/classroom.courses"]


def classroom_add_alias_new():
  """
  Creates a course with alias specification the user has access to.
  The file token.json stores the user's access and refresh tokens, and is
  created automatically when the authorization flow completes for
  the first time.
  Load pre-authorized user credentials from the environment.
  TODO(developer) - See https://developers.google.com/identity for
   guides on implementing OAuth2 for the application.
  """
  # pylint: disable=maybe-no-member
  creds = None
  if os.path.exists("token.json"):
    creds = Credentials.from_authorized_user_file("token.json", SCOPES)
  # If there are no (valid) credentials available, let the user log in.
  if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
      creds.refresh(Request())
    else:
      flow = InstalledAppFlow.from_client_secrets_file(
          "credentials.json", SCOPES
      )
      creds = flow.run_local_server(port=0)
    # Save the credentials for the next run
    with open("token.json", "w", encoding="utf8") as token:
      token.write(creds.to_json())

  alias = "d:school_physics_333"
  course = {
      "id": alias,
      "name": "English",
      "section": "Period 2",
      "description": "Course Description",
      "room": "301",
      "ownerId": "me",
  }
  try:
    print("-------------")
    service = build("classroom", "v1", credentials=creds)
    course = service.courses().create(body=course).execute()
    print("====================================")

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


if __name__ == "__main__":
  # pylint: disable=too-many-arguments
  # Put the course_id of course whose alias needs to be created.
  classroom_add_alias_new()

افزودن نام مستعار برای یک دوره موجود

برای افزودن نام مستعار به یک دوره موجود ، می‌توانید فیلد alias را تنظیم کرده و از متد courses.aliases.create() استفاده کنید.

اسکریپت برنامه‌ها

class/snippets/addAlias.gs
/**
 * Updates the section and room of Google Classroom.
 * @param {string} course_id
 * @see https://developers.google.com/classroom/reference/rest/v1/courses.aliases/create
 */
function addAlias(course_id) {
  const alias = {
    alias: "p:bio_101",
  };
  try {
    const course_alias = Classroom.Courses.Aliases.create(alias, course_id);
    console.log("%s successfully added as an alias!", course_alias.alias);
  } catch (err) {
    // TODO (developer) - Handle exception
    console.log(
      "Request to add alias %s failed with error %s.",
      alias.alias,
      err.message,
    );
  }
}

جاوا

class/snippets/src/main/java/AddAliasToCourse.java
/* Create a new CourseAlias object with a project-wide alias. Project-wide aliases use a prefix
of "p:" and can only be seen and used by the application that created them. */
CourseAlias content = new CourseAlias().setAlias("p:biology_10");
CourseAlias courseAlias = null;

try {
  courseAlias = service.courses().aliases().create(courseId, content).execute();
  System.out.printf("Course alias created: %s \n", courseAlias.getAlias());
} catch (GoogleJsonResponseException e) {
  // TODO (developer) - handle error appropriately
  GoogleJsonError error = e.getDetails();
  if (error.getCode() == 409) {
    System.out.printf("The course alias already exists: %s.\n", content);
  } else {
    throw e;
  }
} catch (Exception e) {
  throw e;
}
return courseAlias;

پایتون

کلاس/قطعه قطعه/کلاس_اضافه_نام مستعار_موجود.py
def classroom_add_alias_existing(course_id):
  """
  Adds alias 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
  service = build("classroom", "v1", credentials=creds)
  alias = "d:school_math_101"
  course_alias = {"alias": alias}
  try:
    course_alias = (
        service.courses()
        .aliases()
        .create(courseId=course_id, body=course_alias)
        .execute()
    )
    return course_alias
  except HttpError as error:
    print(f"An error occurred: {error}")
    print("Alias Creation Failed")
  return course_alias


if __name__ == "__main__":
  # Put the course_id of course whose alias needs to be added.
  classroom_add_alias_existing(456058313539)

بازیابی نام‌های مستعار دوره

شما می‌توانید نام‌های مستعار یک دوره را با استفاده از متد courses.aliases.list() بازیابی کنید، همانطور که در نمونه زیر نشان داده شده است:

دات نت

class/snippets/ClassroomSnippets/ListCourseAliases.cs
using System;
using System.Collections.Generic;
using Google;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Classroom.v1;
using Google.Apis.Classroom.v1.Data;
using Google.Apis.Services;

namespace ClassroomSnippets
{
    // Class to demonstrate the use of Classroom List Alias API
    public class ListCourseAliases
    {
        /// <summary>
        /// Retrieve the aliases for a course.
        /// </summary>
        /// <param name="courseId">Id of the course.</param>
        /// <returns>list of course aliases, null otherwise.</returns>
        public static List<CourseAlias> ClassroomListAliases(string courseId)
        {
            try
            {
                /* Load pre-authorized user credentials from the environment.
                 TODO(developer) - See https://developers.google.com/identity for 
                 guides on implementing OAuth2 for your application. */
                GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                    .CreateScoped(ClassroomService.Scope.ClassroomCourses);

                // Create Classroom API service.
                var service = new ClassroomService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Classroom Snippets"
                });

                string pageToken = null;
                var courseAliases = new List<CourseAlias>();

                do
                {
                    // List of aliases of specified course
                    var request = service.Courses.Aliases.List(courseId);
                    request.PageSize = 100;
                    request.PageToken = pageToken;
                    var response = request.Execute();
                    courseAliases.AddRange(response.Aliases);
                    pageToken = response.NextPageToken;
                } while (pageToken != null);

                if (courseAliases.Count == 0)
                {
                    Console.WriteLine("No aliases found.");
                }
                else
                {
                    Console.WriteLine("Aliases:");
                    foreach (var courseAlias in courseAliases)
                    {
                        Console.WriteLine(courseAlias.Alias);
                    }
                }
                return courseAliases;
            }
            catch (Exception e)
            {
                // TODO(developer) - handle error appropriately
                if (e is AggregateException)
                {
                    Console.WriteLine("Credential Not found");
                }
                else if (e is GoogleApiException)
                {
                    Console.WriteLine("Course does not exist.");
                }

                else
                {
                    throw;
                }
            }
            return null;
        }
    }
}

جاوا

class/snippets/src/main/java/ListCourseAliases.java
String pageToken = null;
List<CourseAlias> courseAliases = new ArrayList<>();

try {
  // List of aliases of specified course
  do {
    ListCourseAliasesResponse response =
        service
            .courses()
            .aliases()
            .list(courseId)
            .setPageSize(100)
            .setPageToken(pageToken)
            .execute();
    courseAliases.addAll(response.getAliases());
    pageToken = response.getNextPageToken();
  } while (pageToken != null);

  if (courseAliases.isEmpty()) {
    System.out.println("No aliases found.");
  } else {
    System.out.println("Aliases:");
    for (CourseAlias courseAlias : courseAliases) {
      System.out.println(courseAlias.getAlias());
    }
  }
} catch (GoogleJsonResponseException e) {
  // TODO(developer) - handle error appropriately
  GoogleJsonError error = e.getDetails();
  if (error.getCode() == 404) {
    System.err.println("Course does not exist.\n");
  } else {
    throw e;
  }
}
return courseAliases;

پایتون

class/snippets/classroom_list_course_aliases.py
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def classroom_list_course_aliases(course_id):
  """
  Prints the list of the aliases of a specified course 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()
  try:
    service = build("classroom", "v1", credentials=creds)
    course_aliases = []
    page_token = None

    while True:
      response = (
          service.courses()
          .aliases()
          .list(pageToken=page_token, courseId=course_id)
          .execute()
      )
      course_aliases.extend(response.get("aliases", []))
      page_token = response.get("nextPageToken", None)
      if not page_token:
        break

    if not course_aliases:
      print("No course aliases found.")

    print("Course aliases:")
    for course_alias in course_aliases:
      print(f"{course_alias.get('alias')}")
    return course_aliases
  except HttpError as error:
    print(f"An error occurred: {error}")
    return error


if __name__ == "__main__":
  classroom_list_course_aliases("course_id")