【发布时间】:2019-11-12 18:48:22
【问题描述】:
在使用 Google Docs API 将某些 Unicode 字符写入 Google Doc 时,我被 400 状态困扰:
HttpError:https://docs.googleapis.com/v1/documents/xxxxxxxxx:batchUpdate?alt=json 返回“无效请求[0].insertText:插入索引不能位于字素簇内。”>
我已设法将其归结为最小的示例。下面的例程尝试插入(按顺序):
- 泰文字符串
'ถ้ามีลูกแล้วไม่ส่งเรียนพิเศษอะไรเลย จะเป็นอะไรไหมครับ' - 在上述字符串上方/之前的换行符
代码:
from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build
SCOPES = [
"https://www.googleapis.com/auth/documents",
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/drive.appdata",
"https://www.googleapis.com/auth/drive.metadata",
]
credentials = Credentials.from_service_account_file("data/gdocscredentials.json", scopes=SCOPES)
svc = build("docs", "v1", credentials=credentials).documents()
requests = [
{
"insertText": {
"location": {
# The zero-based index, in UTF-16 code units
"index": 1
},
"text": "ถ้ามีลูกแล้วไม่ส่งเรียนพิเศษอะไรเลย จะเป็นอะไรไหมครับ"
}
},
{"insertText": {"location": {"index": 1}, "text": "\n"}}
]
svc.batchUpdate(
documentId="xxxxxxxxx",
body={"requests": requests}
).execute()
因此,错误暗示泰语字符串包含(或存在)字素簇。 docs refer to this:
API 可能会隐式调整位置以防止插入 Unicode 字素簇。发生这种情况时,文本会立即插入到字素簇之后。
如何正确纠正此错误?
Google mentions that索引以 UTF-16 代码单元衡量。但这似乎并不重要,因为此代码 sn-p 使用的是同一文档页面本身推荐的“向后工作”方法。
【问题讨论】:
标签: python python-3.x google-docs google-docs-api