
Google Forms API本身不提供在特定Google Drive文件夹中创建表单的功能。本教程将指导您如何结合使用Google Drive API和Google Forms API,首先利用Drive API在目标文件夹中创建表单的占位符文件,然后使用Forms API填充表单内容,从而实现在指定位置创建Google表单。
引言
在使用Python通过Google Forms API创建Google表单时,一个常见的限制是无法直接指定表单的存储位置。默认情况下,所有新创建的表单都会被放置在您的Google Drive根目录中。这对于需要将表单组织到特定项目或分类文件夹中的用户来说,带来了额外的手动管理负担。Google Forms API的文档中并未提供类似parents这样的参数来在创建时指定父文件夹。
解决方案核心:整合Google Drive API
要解决这一问题,我们需要理解Google表单在Google生态系统中的本质:它被视为Google Drive中的一种特殊文件类型(MIME类型为application/vnd.google-apps.form)。因此,我们可以利用Google Drive API的强大功能来管理这些“文件”的位置。
核心思路是:
立即学习“Python免费学习笔记(深入)”;
- 利用Google Drive API在目标文件夹中创建一个指定MIME类型的空白表单文件。这样,表单的“壳”就直接创建在了我们想要的文件夹中,并获得了其唯一的表单ID。
- 利用Google Forms API,通过上一步获取到的表单ID,对这个空白表单进行内容填充和属性更新(例如设置标题、添加问题等)。
通过这种两步走的策略,我们既能利用Drive API的文件夹管理能力,又能利用Forms API的表单内容编辑能力。
前置准备:API客户端和服务认证
在开始编写代码之前,请确保您已完成以下准备工作:
-
安装必要的库:
pip install google-api-python-client google-auth-oauthlib google-auth-httplib2
启用Google API: 在Google Cloud Console中,为您的项目启用“Google Drive API”和“Google Forms API”。
-
设置认证凭据: 下载您的OAuth 2.0客户端凭据文件(通常命名为credentials.json),并将其放置在您的Python脚本同一目录下。 您需要配置正确的API作用域(Scopes)。对于本教程,以下作用域是推荐的:
- https://www.googleapis.com/auth/drive.file:允许访问和管理应用程序创建或打开的文件。
- https://www.googleapis.com/auth/forms.body:允许查看、编辑、创建和删除Google表单的内容。
- https://www.googleapis.com/auth/forms.responses.readonly:如果您还需要读取表单响应,则需要此作用域。
以下是认证代码的通用模板:
import os 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 # 定义API作用域 SCOPES = [ "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/forms.body" ] creds = None # token.json 存储了用户上一次授权的凭据,如果存在,则直接加载 if os.path.exists("token.json"): creds = Credentials.from_authorized_user_file("token.json", SCOPES) # 如果没有有效的凭据,则让用户登录 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) # 将凭据保存到 token.json,以便下次使用 with open("token.json", "w") as token: token.write(creds.to_json()) # 构建Drive和Forms服务客户端 drive_service = build("drive", "v3", credentials=creds) form_service = build("forms", "v1", credentials=creds)
操作步骤详解
接下来,我们将详细介绍如何实现上述两步策略。
1. 获取目标文件夹ID
首先,您需要知道目标Google Drive文件夹的ID。您可以通过以下方式获取:
- 打开Google Drive,导航到您希望创建表单的文件夹。
- 查看浏览器地址栏中的URL,文件夹ID通常是folders/后面的一串字符。 例如:https://drive.google.com/drive/folders/YOUR_FOLDER_ID_HERE
# 替换为您的目标文件夹ID target_folder_id = "YOUR_TARGET_FOLDER_ID"
2. 通过Drive API在指定文件夹中创建空白Google表单
使用drive_service.files().create()方法来创建文件。关键在于设置正确的mimeType为application/vnd.google-apps.form,并指定parents参数为目标文件夹ID。
# 文件元数据,指定名称、MIME类型和父文件夹
file_metadata = {
"name": "我的新项目表单", # 这是在Drive中显示的文件名
"mimeType": "application/vnd.google-apps.form",
"parents": [target_folder_id]
}
try:
# 创建文件,并请求返回文件ID
created_file = drive_service.files().create(
body=file_metadata,
fields="id"
).execute()
form_id = created_file.get("id")
print(f"空白表单已在指定文件夹中创建,ID: {form_id}")
except Exception as e:
print(f"创建表单文件时发生错误: {e}")
form_id = None # 确保在出错时form_id为None执行此步骤后,一个名为“我的新项目表单”的空白Google表单将出现在您指定的Google Drive文件夹中。form_id变量将包含此新表单的唯一标识符。
3. 通过Forms API填充和更新表单内容
现在我们有了form_id,可以使用form_service.forms().batchUpdate()方法来修改表单的标题、描述以及添加问题等。
if form_id:
# 构建更新请求体
# 这里我们更新表单的标题和文档标题,并添加一个文本问题
update_requests = {
"requests": [
{
"updateFormInfo": {
"info": {
"title": "项目反馈表单", # 这是表单在Forms界面中显示的标题
"documentTitle": "项目反馈表单 - 2023 Q4" # 这是Drive中显示的文件名,与name一致更佳
},
"updateMask": "title,documentTitle"
}
},
{
"createItem": {
"item": {
"title": "您的姓名?",
"questionItem": {
"question": {
"textQuestion": {
"paragraph": False
}
}
}
},
"location": {
"index": 0 # 在表单开头添加
}
}
},
{
"createItem": {
"item": {
"title": "您对本次项目的总体评价是?",
"questionItem": {
"question": {
"choiceQuestion": {
"type": "RADIO",
"options": [
{"value": "非常满意"},
{"value": "满意"},
{"value": "一般"},
{"value": "不满意"}
]
}
}
}
},
"location": {
"index": 1 # 在第一个问题之后添加
}
}
}
]
}
try:
# 执行批量更新操作
form_service.forms().batchUpdate(
formId=form_id,
body=update_requests
).execute()
print(f"表单 '{form_id}' 内容已成功更新。")
except Exception as e:
print(f"更新表单内容时发生错误: {e}")
else:
print("无法更新表单,因为表单ID无效。")完整代码示例
将上述认证、创建和更新步骤整合到一个脚本中:
import os
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
# --- 1. 认证和API服务构建 ---
SCOPES = [
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/forms.body"
]
creds = None
if os.path.exists("token.json"):
creds = Credentials.from_authorized_user_file("token.json", SCOPES)
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)
with open("token.json", "w") as token:
token.write(creds.to_json())
drive_service = build("drive", "v3", credentials=creds)
form_service = build("forms", "v1", credentials=creds)
# --- 2. 定义目标文件夹ID ---
# 替换为您的目标文件夹ID
target_folder_id = "YOUR_TARGET_FOLDER_ID"
if target_folder_id == "YOUR_TARGET_FOLDER_ID":
print("错误:请将 'YOUR_TARGET_FOLDER_ID' 替换为实际的Google Drive文件夹ID。")
exit()
form_id = None
try:
# --- 3. 通过Drive API在指定文件夹中创建空白Google表单 ---
file_metadata = {
"name": "我的新项目表单",
"mimeType": "application/vnd.google-apps.form",
"parents": [target_folder_id]
}
created_file = drive_service.files().create(
body=file_metadata,
fields="id"
).execute()
form_id = created_file.get("id")
print(f"空白表单已在指定文件夹中创建,ID: {form_id}")
# --- 4. 通过Forms API填充和更新表单内容 ---
if form_id:










