使用幻灯片 API 替换谷歌幻灯片图像

问题描述 投票:0回答:1

我有以下脚本来更新谷歌幻灯片中的图像,它工作正常,但有时会给我 400 错误,服务帐户对驱动器/图像和演示文稿具有写入权限

image_mappings = {
    "id_in_presenation": "name_of_the_image",
    "id_in_presenation1": "name_of_the_image1",
}

# listing .png files 
def get_png_files(drive_folder_id, drive_service):
    query = f"'{drive_folder_id}' in parents and mimeType='image/png'"
    results = drive_service.files().list(q=query, supportsAllDrives=True, fields="files(id, name, webViewLink, webContentLink)").execute()
    drive_png_files = results.get('files', [])
    print('drive_png_files', drive_png_files)
    return drive_png_files`


# updating images in slides

def update_images_in_slides(drive_png_files, slides_service, presentation_id):
    """
    Updates images in a Google Slides presentation.

    Args:
    drive_png_files: A list of .png files from Google Drive.
    slides_service: The authenticated Google Slides service object.
    presentation_id: The ID of the presentation to update.
    """

    requests = []
    for slide_image_id, new_image_name in info.image_mappings.items():
        drive_file = next((item for item in drive_png_files if item['name'] == new_image_name), None)
        if drive_file:
            requests.append({
                'replaceImage': {
                    'imageObjectId': slide_image_id,
                    'imageReplaceMethod': 'CENTER_INSIDE',
                    'url': f'https://drive.google.com/uc?id={drive_file["id"]}'
                }
            })
    if requests:
        body = {'requests': requests}
        try:
            response = slides_service.presentations().batchUpdate(presentationId=presentation_id, body=body).execute()
            time.sleep(10)
            print(f"\nUpdated the slide: {response}")
        except Exception as exc:
            raise ValueError(f"Failed to update the presentation.") from exc

向编辑和作者授予驱动器、图像、演示文稿的服务帐户的访问权限没有帮助

python service-accounts presentation google-slides-api google-slides
1个回答
0
投票

根据你的问题,我猜测出以下问题。

  1. 可能包含未公开共享的图像文件。
  2. 可能包含超过最大图像尺寸的图像文件。 参考

出现这些问题时,会出现状态码 400 的错误。但是,不幸的是,我无法从您的问题中知道您的实际错误消息。当我的猜测正确时,下面的修改如何?

修改后的脚本:

在此修改中,您的功能

update_images_in_slides
被修改。

为了使用 Drive API,请在最后一个参数中添加

drive_service
。请注意这一点。

def update_images_in_slides(drive_png_files, slides_service, presentation_id, drive_service):
    """
    Updates images in a Google Slides presentation.

    Args:
    drive_png_files: A list of .png files from Google Drive.
    slides_service: The authenticated Google Slides service object.
    presentation_id: The ID of the presentation to update.
    """

    # Images are publicly shared for inserting to Slide.
    batch1 = drive_service.new_batch_http_request()
    for e in drive_png_files:
        batch1.add(drive_service.permissions().create(fileId=e["id"], body={"type": "anyone", "role": "reader"}, supportsAllDrives=True))
    batch1.execute()

    requests = []
    for slide_image_id, new_image_name in info.image_mappings.items():
        drive_file = next((item for item in drive_png_files if item['name'] == new_image_name), None)
        if drive_file:
            requests.append({
                'replaceImage': {
                    'imageObjectId': slide_image_id,
                    'imageReplaceMethod': 'CENTER_INSIDE',
                    # 'url': f'https://drive.google.com/uc?id={drive_file["id"]}'
                    'url': f'https://drive.google.com/thumbnail?sz=w1000&id={drive_file["id"]}'
                }
            })
    if requests:
        body = {'requests': requests}
        try:
            response = slides_service.presentations().batchUpdate(presentationId=presentation_id, body=body).execute()
            time.sleep(10)
            print(f"\nUpdated the slide: {response}")
        except Exception as exc:
            raise ValueError(f"Failed to update the presentation.") from exc

    # Permission of publicly shared images is removed.
    batch2 = drive_service.new_batch_http_request()
    for e in drive_png_files:
        batch2.add(drive_service.permissions().delete(fileId=e["id"], permissionId="anyoneWithLink", supportsAllDrives=True))
    batch2.execute()
  • 当我测试这个修改后的脚本时,我确认该脚本可以正常工作。

注:

  • 此修改后的脚本假设您的

    drive_png_files, slides_service, presentation_id, drive_service
    info.image_mappings
    值是有效值。请注意这一点。

  • 在此修改中,使用以下流程。

    1. 图像文件公开共享。
    2. 将公开分享的图像放在幻灯片上。
    3. 删除公开分享权限。
  • 我无法知道您当前的范围。因此,当错误与范围相关时,请在当前范围中添加

    https://www.googleapis.com/auth/drive
    的范围,然后再次测试。请注意这一点。

  • 如果所有图像的图像大小都是不同的大小,我想

    'url': f'https://drive.google.com/uc?id={drive_file["id"]}'
    可能可以使用。

参考

© www.soinside.com 2019 - 2024. All rights reserved.