【问题标题】:python program to insert jpg files into a google slides presentationpython程序将jpg文件插入谷歌幻灯片演示文稿
【发布时间】:2021-02-13 09:27:46
【问题描述】:

下一次尝试: 假设我有一个包含 jpg 图像文件的目录,并且最早的图像(时间戳)应该是幻灯片 #1,而最新的图像幻灯片 #N 要插入到谷歌幻灯片演示文稿中。我正在使用the API Windows 10 上的安装显然没问题。 之前报告的问题已经修复,感谢帮助我的人。

接下来,这段 python 代码是为了检查 API 是否适合我:(与我第一次创建这篇文章相比修改了)

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import library_JP

# If modifying these scopes, delete the file token.pickle.
#SCOPES = ['https://www.googleapis.com/auth/presentations.readonly']
SCOPES = ['https://www.googleapis.com/auth/presentations']

# The ID of a sample presentation.
PRESENTATION_ID = '1EAYk18WDjIG-zp_0vLm3CsfQh_i8eXc67Jo2O9C6Vuc'

def main():
    """Shows basic usage of the Slides API.
    Prints the number of slides and elments in a sample presentation.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # 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(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('slides', 'v1', credentials=creds)

    # Call the Slides API
    IMAGE_URL = ('https://www.google.com/images/branding/'
             'googlelogo/2x/googlelogo_color_272x92dp.png')
    requests = []
    page_id = '3b330c04-6eb2-11eb-9439-0242ac130002'
    image_id = 'MyImage_01'
    emu4M = {
    'magnitude': 4000000,
    'unit': 'EMU',
            }
    requests.append({
     'createImage': {
        'objectId': image_id,
        'url': IMAGE_URL,
        'elementProperties': {
            'pageObjectId': page_id,
            'size': {
                'height': emu4M,
                'width': emu4M
            },
            'transform': {
                'scaleX': 1,
                'scaleY': 1,
                'translateX': 100000,
                'translateY': 100000,
                'unit': 'EMU'
                         }
            }
                    }
                    })
    title = 'JP_february13-2021 '
    body = {
    'title': title, 'requests': requests
    }
#    presentation = slides_service.presentations() \
    presentation = service.presentations() \
    .create(body=body).execute()
    print('Created presentation with ID: {0}'.format(
    presentation.get('presentationId')))
    response = slides_service.presentations() \
    .batchUpdate(presentationId=presentation_id, body=body).execute()
    create_image_response = response.get('replies')[0].get('createImage')
    print('Created image with ID: {0}'.format(
    create_image_response.get('objectId')))





if __name__ == '__main__':
    main()


请注意,我已将代码包含在 https://github.com/googleworkspace/python-samples/blob/master/slides/snippets/slides_snippets.py 如下:

import library_JP

现在有一个新问题:

python quickstart_JP1.py
Please visit this URL to authorize this application: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=162352680285-0i0fmpq50gqgsm1d796mmdim3c3oe874.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A53854%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fpresentations&state=I7dMBbrWmZjVXBwyk0i1mAqLFWonhS&access_type=offline
Traceback (most recent call last):
  File "quickstart_JP1.py", line 91, in <module>
    main()
  File "quickstart_JP1.py", line 77, in main
    .create(body=body).execute()
  File "C:\Users\joepareti54\anaconda3\lib\site-packages\googleapiclient\_helpers.py", line 134, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Users\joepareti54\anaconda3\lib\site-packages\googleapiclient\http.py", line 915, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://slides.googleapis.com/v1/presentations?alt=json returned "Invalid JSON payload received. Unknown name "requests": Cannot find field.". Details: "[{'@type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'description': 'Invalid JSON payload received. Unknown name "requests": Cannot find field.'}]}]">

【问题讨论】:

  • 从你的报错信息中,发现你报错信息的原因是https://www.googleapis.com/auth/presentations.readonly的范围。当你想使用presentations().create()的方法时,需要使用https://www.googleapis.com/auth/presentations。但我无法理解您的脚本与Assume that I have a directory with jpg image files, and the oldest image (time stamp) should be slide #1, and the newest image slide #N to be inserted in a google slides presentation. 之间的关系。我可以问你这个问题的目标吗?
  • 感谢您的建议,我可以解决问题。然后我发布了导致下一个异常的代码的修改版本
  • 感谢您的回复。我很高兴你的问题得到了解决。当您的问题解决后,您可以将其发布为答案吗?这样,它对遇到相同问题的其他用户很有用。
  • 这里的问题似乎是请求中缺少 field 参数。但是,我并不是你想要达到的目标?

标签: python google-slides-api google-slides


【解决方案1】:

此代码有效;删除 token.pickle 并具有以下条目很重要:

SCOPES = ['https://www.googleapis.com/auth/presentations']

而不是

SCOPES = ['https://www.googleapis.com/auth/presentations.readonly'] ```

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
#SCOPES = ['https://www.googleapis.com/auth/presentations.readonly']
SCOPES = ['https://www.googleapis.com/auth/presentations']

# The ID of a sample presentation.
PRESENTATION_ID = '1EAYk18WDjIG-zp_0vLm3CsfQh_i8eXc67Jo2O9C6Vuc'

def main():
    """Shows basic usage of the Slides API.
    Prints the number of slides and elments in a sample presentation.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # 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(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('slides', 'v1', credentials=creds)

    # Call the Slides API
    title = 'JP_february13-2021 '
    body = {
    'title': title
    }
#    presentation = slides_service.presentations() \
    presentation = service.presentations() \
    .create(body=body).execute()
    print('Created presentation with ID: {0}'.format(
    presentation.get('presentationId')))

#    print('The presentation contains {} slides:'.format(len(slides)))
#    for i, slide in enumerate(slides):
#        print('- Slide #{} contains {} elements.'.format(
#            i + 1, len(slide.get('pageElements'))))


if __name__ == '__main__':
    main()


但是,我尝试在演示文稿中包含图像的下一个版本确实 不工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-04
    • 2022-09-23
    • 1970-01-01
    • 2021-06-02
    相关资源
    最近更新 更多