【问题标题】:Create Google Document with Python使用 Python 创建 Google 文档
【发布时间】:2020-09-05 13:34:54
【问题描述】:

我正在尝试使用 Google API 创建新的 google 文档(用于请求审查的自动化)

我正在使用来自 Google 的“示例”中的以下代码,但它对我不起作用: https://github.com/gsuitedevs/python-samples/blob/master/docs/quickstart/quickstart.py

执行此脚本时出现错误:

    Traceback (most recent call last):
  File "google_docs.py", line 46, in <module>
    main()
  File "google_docs.py", line 31, in main
    'credentials.json', SCOPES)
  File "/usr/local/lib/python3.7/site-packages/google_auth_oauthlib/flow.py", line 199, in from_client_secrets_file
    return cls.from_client_config(client_config, scopes=scopes, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/google_auth_oauthlib/flow.py", line 159, in from_client_config
    'Client secrets must be for a web or installed app.')
ValueError: Client secrets must be for a web or installed app.

注意:我创建了一个服务帐户,以下代码使用相同的凭据即可正常工作:

import gspread


client = gspread.service_account(filename='credentials.json')

sheet = client.open('Test').sheet1
print(sheet.get_all_records())

所以,我猜这意味着凭据文件是正确的,但我想知道我可以更改哪些内容才能创建 Google 文档,而不仅仅是电子表格...

【问题讨论】:

    标签: python google-authentication


    【解决方案1】:

    经过几个小时的实验和挫折后,我发现了一种肮脏的解决方法:

    import gspread
    from googleapiclient.discovery import build
    
    
    # The ID of a sample document.
    DOCUMENT_ID = '195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE'
    
    client = gspread.service_account(filename='credentials.json')
    
    service = build('docs', 'v1', credentials=client.auth)
    document = service.documents().get(documentId=DOCUMENT_ID).execute()
    print('The title of the document is: {}'.format(document.get('title')))
    

    所以,我会把它放在这里以防万一有人遇到我今天遇到的同样问题:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-20
      • 2016-12-06
      • 1970-01-01
      • 2013-08-28
      • 2021-04-10
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多