【问题标题】:How do I open a file in google docs using google api and python?如何使用 google api 和 python 在 google docs 中打开文件?
【发布时间】:2019-09-11 13:22:57
【问题描述】:

我尝试打开用 python/django 编写的应用程序发送的文件。使用文档link 创建空白文档我尝试传输现有文件以在谷歌文档中打开。

views.py

SCOPES = ['https://www.googleapis.com/auth/documents.readonly']
def file_to_gd_docs(import_file=None):
    .... 
    #authorization part(success)
    ....
    service = build('docs', 'v1', credentials=creds)

    title = 'My Document'
    body = {
        'title': title
    }
    doc = service.documents().create(body=import_file).execute()
    print('Created document with title: {0}'.format(
        doc.get('title')))

我把 import_file 的值作为变量 body 的值 我得到一个错误

googleapiclient.errors.HttpError: <HttpError 403 when requesting https://docs.googleapis.com/v1/documents?alt=json returned "Request had insufficient authentication scopes.">

如何正确地将外部文件传输到 google docs 以进行打开?

【问题讨论】:

    标签: python google-api google-docs-api google-api-python-client


    【解决方案1】:

    Documents.create 需要以下范围之一

    您正在使用https://www.googleapis.com/auth/documents.readonly,这会给您带来错误

    请求的身份验证范围不足。

    解决方案

    将范围更改为所需范围之一并再次请求用户访问。

    【讨论】:

    • @DalmTo 谢谢,这个错误已经消失了,但是有一个新问题&lt;HttpError 400 when requesting https://docs.googleapis.com/v1/documents?alt=json returned "Invalid JSON payload received. Unknown name "": Root element must be a message.". Details: "[{'@type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'description': 'Invalid JSON payload received. Unknown name "": Root element must be a message.'}]}]"&gt; 是否可以在不创建新文件的情况下打开传输的文件?
    • 打开一个新问题,我会试着在早上找时间为你看看。您可能应该使用 libray 来构建 body 对象,但我是 Python 开发新手,我将不得不四处寻找示例
    • @DalmTo 感谢您的帮助,我找到了最适合我的解决方案。首先,我将文件保存在 google 驱动器上,获取其 id 并将其重定向到 google 文档,其中包含收到的 id 链接,如 return (f"https://docs.google.com/document/d/{file.get('id')}/edit")
    【解决方案2】:

    这取决于你为什么想要这个。上面是正确的方法,使用google的api,但您也可以使用以下hack:
    网址 = https://docs.google.com/document/u/0/ webbrowser.open(url)

    然后使用 pyautogui 最​​大化或平铺窗口并单击新建。这仅适用于一种尺寸的显示器。如果您移动到另一个系统,则需要更改 pyautogui 单击的位置。此外,如果 Google 更改页面布局,它可能会中断。

    当我想听写一个笔记时,我会使用我的语音助手来执行此操作。它只适合我而不是分发;那为什么不呢?我不希望我的 api 密钥在我的代码中出现在 github 上。对于许多共享代码但需要 api 密钥的人来说,这是一个痛苦。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      相关资源
      最近更新 更多