使用服务帐户,我尝试在该帐户可用的根文件夹中创建一个文件夹,并将图像上传到创建的文件夹。
async def create_folder(api, parent, name):
return await api.as_service_account(
drive.files.create(
json = {
'mimeType': 'application/vnd.google-apps.folder',
'name': name,
'parents': [parent]
},
)
)
async def upload_file(api, path, parent, name):
return await api.as_service_account(
drive.files.create(
upload_file = path,
json = {
'name': name,
'parents': [parent]
},
fields = "id, name, webViewLink, webContentLink",
)
)
async def update_doc(api, id, requests):
return await api.as_service_account(
docs.documents.batchUpdate(
documentId = id,
json = {
"requests": requests
}
)
)
def insert_image(uri, index):
return {
"insertInlineImage": {
"uri": uri,
"location": {
"index": index
},
"objectSize": {
"height": {
"magnitude": 125,
"unit": "PT"
},
}
}
}
async def main(parent_id, path, file, doc_id):
async with client.api: # my "wrapper" around Aiogoogle
folder = await create_folder(
client.api,
parent_id,
"A folder in root folder"
)
image = await upload_file(
client.api,
f"{path}/{file}",
folder["id"],
"A file in created folder",
)
await update_doc(
client.api,
doc_id,
[insert_image(image["webContentLink"], 0)]
)
虽然文件和文件夹实际上都已创建(它甚至说该帐户是它们的所有者),但我收到此错误:
{'code': 400,
'message': 'Invalid requests[0].insertInlineImage: Access to the provided '
'image was forbidden.',
'status': 'INVALID_ARGUMENT'}
我尝试将这些参数提供给两个drive.files.create() 调用:
includePermissionsForView = "published",
ignoreDefaultVisibility = True
,但运气不佳
我认为当使用Docs API将图像使用
webContentLink
放入Google文档时,图像需要公开共享。那么根据您的情况,以下模式怎么样?
在此模式中,使用
webContentLink
。请使用Drive API中的“权限:创建”方法公开共享上传的文件。 参考
这样,您就可以使用
webContentLink
放置上传的图像。但现阶段存在该链接无法使用的情况。 Ref 我认为这可能是一个错误或当前的规范。
因此,作为一种解决方法,我想提出另一种模式。
在此模式中,通过修改查询参数,使用
thumbnailLink
代替 webContentLink
。在这种情况下,不需要公开共享上传的文件。
请在字段中添加
thumbnailLink
,例如 fields = "id, name, webViewLink, webContentLink, thumbnailLink",
表示 drive.files.create
。这样,thumbnailLink
就包含在返回值中。 thumbnailLink
的值如下。
https://lh3.googleusercontent.com/###=s220
请将
=s220
修改为=s1000
。由此,图像宽度的图像尺寸变大。此外,您可以自由更改此设置。请使用此修改后的 URL insertInlineImage
。
经过长时间的搜索,这确实是我找到的解决此错误的唯一方法。谷歌还没有解决这个问题,真是太疯狂了。但是,我设法用这个解决方案解决了这个问题。再次感谢。
它似乎与这个已知的错误有关:https://issuetracker.google.com/issues/150933939