یک فرم یا مسابقه ایجاد کنید

این صفحه نحوه انجام این وظایف مربوط به فرم‌ها را شرح می‌دهد:

  • ایجاد فرم جدید
  • کپی کردن یک فرم موجود
  • تبدیل فرم به آزمون

قبل از اینکه شروع کنی

قبل از ادامه‌ی وظایف این صفحه، وظایف زیر را انجام دهید:

  • مجوز یا احراز هویت کامل و تنظیمات اعتبارنامه‌ها را در دستورالعمل‌های برنامه‌ی پذیرندگان اولیه انجام دهید.
  • مرور کلی API فرم‌ها را مطالعه کنید.

ایجاد فرم جدید

ایجاد اولیه یک فرم فقط به یک فیلد عنوان نیاز دارد - هر فیلد دیگری در درخواست نادیده گرفته می‌شود. برای ساخت محتوا و ابرداده یک فرم یا ایجاد به‌روزرسانی‌ها، از متد batchUpdate() استفاده کنید. برای اطلاعات بیشتر به بخش به‌روزرسانی فرم یا آزمون مراجعه کنید.

استراحت

متد forms.create() را فقط با یک عنوان فراخوانی کنید.

متن درخواست نمونه

{
  "info": {
      "title": "My new form"
  }
}

پایتون

فرم‌ها/قطعه کدها/create_form.py
from apiclient import discovery
from httplib2 import Http
from oauth2client import client, file, tools

SCOPES = "https://www.googleapis.com/auth/drive"
DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1"

store = file.Storage("token.json")
creds = None
if not creds or creds.invalid:
  flow = client.flow_from_clientsecrets("client_secrets.json", SCOPES)
  creds = tools.run_flow(flow, store)

form_service = discovery.build(
    "forms",
    "v1",
    http=creds.authorize(Http()),
    discoveryServiceUrl=DISCOVERY_DOC,
    static_discovery=False,
)

form = {
    "info": {
        "title": "My new form",
    },
}
# Prints the details of the sample form
result = form_service.forms().create(body=form).execute()
print(result)

نود جی اس

فرم‌ها/قطعه کدها/create_form.js
import path from 'node:path';
import {authenticate} from '@google-cloud/local-auth';
import {forms} from '@googleapis/forms';

/**
 * Creates a new form.
 */
async function createForm() {
  // Authenticate with Google and get an authorized client.
  const authClient = await authenticate({
    keyfilePath: path.join(__dirname, 'credentials.json'),
    scopes: 'https://www.googleapis.com/auth/drive',
  });

  // Create a new Forms API client.
  const formsClient = forms({
    version: 'v1',
    auth: authClient,
  });

  // The request body to create a new form.
  const newForm = {
    info: {
      title: 'Creating a new form in Node',
    },
  };

  // Send the request to create the form.
  const result = await formsClient.forms.create({
    requestBody: newForm,
  });

  console.log(result.data);
  return result.data;
}

کپی کردن یک فرم موجود

شما می‌توانید یک فرم موجود را با استفاده از Google Drive API کپی کنید تا استفاده مجدد از محتوا آسان‌تر شود. می‌توانید شناسه فرم را در URL فرم‌های Google پیدا کنید:

https://docs.google.com/forms/d/FORM_ID/edit

استراحت

متد files.copy() از API گوگل درایو را با شناسه فرمی که می‌خواهید کپی کنید، فراخوانی کنید.

پایتون

forms/snippets/duplicate_form.py
import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

# If modifying these scopes, delete the file token.json.
SCOPES = ["https://www.googleapis.com/auth/drive"]


def main():
  """Shows copy file example in Drive v3 API.
  Prints the name, id and other data of the copied file.
  """
  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(
          "client_secrets.json", SCOPES
      )
      creds = flow.run_local_server(port=0)
    # Save the credentials for the next run
    with open("token.json", "w") as token:
      token.write(creds.to_json())

  service = build("drive", "v3", credentials=creds)

  # Call the Drive v3 API
  origin_file_id = "1ox-6vHFeKpC6mon-tL5ygBC8zpbTnTp76JCZdIg80hA"  # example ID
  copied_file = {"title": "my_copy"}
  results = (
      service.files().copy(fileId=origin_file_id, body=copied_file).execute()
  )
  print(results)


if __name__ == "__main__":
  main()

تبدیل فرم به آزمون

برای ایجاد یک آزمون، ابتدا یک فرم مطابق آنچه در بخش «ایجاد فرم جدید» توضیح داده شده است، ایجاد کنید، سپس تنظیمات فرم را به‌روزرسانی کنید. این به‌روزرسانی به شناسه فرم نیاز دارد.

استراحت

برای تنظیم مقدار isQuiz روی true، متد batch.update() را روی یک فرم موجود فراخوانی کنید.

متن درخواست نمونه

{
  "requests": [
    {
      "updateSettings": {
        "settings": {
          "quizSettings": {
            "isQuiz": true
          }
        },
        "updateMask": "quizSettings.isQuiz"
      }
    }
  ]
}

پایتون

forms/snippets/convert_form.py
from apiclient import discovery
from httplib2 import Http
from oauth2client import client, file, tools

SCOPES = "https://www.googleapis.com/auth/forms.body"
DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1"

store = file.Storage("token.json")
creds = None
if not creds or creds.invalid:
  flow = client.flow_from_clientsecrets("client_secrets.json", SCOPES)
  creds = tools.run_flow(flow, store)

form_service = discovery.build(
    "forms",
    "v1",
    http=creds.authorize(Http()),
    discoveryServiceUrl=DISCOVERY_DOC,
    static_discovery=False,
)

form = {
    "info": {
        "title": "My new quiz",
    }
}

# Creates the initial form
result = form_service.forms().create(body=form).execute()

# JSON to convert the form into a quiz
update = {
    "requests": [
        {
            "updateSettings": {
                "settings": {"quizSettings": {"isQuiz": True}},
                "updateMask": "quizSettings.isQuiz",
            }
        }
    ]
}

# Converts the form into a quiz
question_setting = (
    form_service.forms()
    .batchUpdate(formId=result["formId"], body=update)
    .execute()
)

# Print the result to see it's now a quiz
getresult = form_service.forms().get(formId=result["formId"]).execute()
print(getresult)

نود جی اس

فرم‌ها/قطعه کدها/convert_form.js
import path from 'node:path';
import {authenticate} from '@google-cloud/local-auth';
import {forms} from '@googleapis/forms';

/**
 * Creates a new form and then converts it into a quiz.
 */
async function convertForm() {
  // Authenticate with Google and get an authorized client.
  const authClient = await authenticate({
    keyfilePath: path.join(__dirname, 'credentials.json'),
    scopes: 'https://www.googleapis.com/auth/drive',
  });

  // Create a new Forms API client.
  const formsClient = forms({
    version: 'v1',
    auth: authClient,
  });

  // The initial form to be created.
  const newForm = {
    info: {
      title: 'Creating a new form for batchUpdate in Node',
    },
  };

  // Create the new form.
  const createResponse = await formsClient.forms.create({
    requestBody: newForm,
  });

  if (!createResponse.data.formId) {
    throw new Error('Failed to create form.');
  }

  console.log(`New formId was: ${createResponse.data.formId}`);

  // Request body to convert the form to a quiz.
  const updateRequest = {
    requests: [
      {
        updateSettings: {
          settings: {
            quizSettings: {
              isQuiz: true,
            },
          },
          // The updateMask specifies which fields to update.
          updateMask: 'quizSettings.isQuiz',
        },
      },
    ],
  };

  // Send the batch update request to convert the form to a quiz.
  const result = await formsClient.forms.batchUpdate({
    formId: createResponse.data.formId,
    requestBody: updateRequest,
  });

  console.log(result.data);
  return result.data;
}

مراحل بعدی

در اینجا چند مرحله بعدی وجود دارد که می‌توانید امتحان کنید: