【问题标题】:Google API is not creating any document in the drive when I'm trying to create a blank document using python当我尝试使用 python 创建一个空白文档时,Google API 没有在驱动器中创建任何文档
【发布时间】:2022-01-18 10:45:13
【问题描述】:

我正在尝试下面的代码来生成谷歌文档

    SERVICE_FILENAME = 'C:/Users/XYZ/Test/service_account.json'  # set path to service account filename
    
    from googleapiclient.discovery import build
    from google.oauth2 import service_account
    
    from googleapiclient.http import MediaIoBaseDownload, MediaFileUpload
    
    credentials = service_account.Credentials.from_service_account_file(SERVICE_FILENAME,
                                                                        scopes=['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/documents']
                                                                        )
    
    # drive = build('drive', 'v3', credentials=credentials)
    drive = build('docs', 'v1', credentials=credentials)
    # file_metadata = {'name': filepath,
    #                  'mimeType': 'application/vnd.google-apps.document'}

    # media = MediaFileUpload(filepath,
    #                          mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
    # file = drive.files().create(body=file_metadata,
    #                             # media_body=media,
    #                             fields='id').execute()
    file_metadata = {
        "title": "xyz",
        "body": {}
    }

    file = drive.documents().create(body=file_metadata).execute()
    print('File ID: %s' % file.get('id'))
    

但我没有得到任何文件 ID,也没有在 google 文档中创建文件。它说File ID: None

首先,尝试使用驱动器 API,但没有成功,然后我选择了也无法正常工作的 doc API。 注意:这两个 API 都是从 GCP 启用的。

@Tanaike 评论后我使用的方法:

from googleapiclient.discovery import build
from google.oauth2 import service_account

SERVICE_FILENAME = 'C:/Users/Test/service_account.json'  # set path to service account filename
credentials = service_account.Credentials.from_service_account_file(SERVICE_FILENAME,
                                                                    scopes=['https://www.googleapis.com/auth/drive']
                                                                    )

drive = build('drive', 'v3', credentials=credentials)

page_token = None
response = drive.files().list(q="mimeType = 'application/vnd.google-apps.folder'",
                              spaces='drive',
                              fields='nextPageToken, files(id, name)',
                              pageToken=page_token).execute()
for file in response.get('files', []):
    # Process change
    print('Found file: %s (%s)' % (file.get('name'), file.get('id')))
    if file.get('name') == "Document_API":
        folder_id = file.get('id')
        break
    page_token = response.get('nextPageToken', None)
    if page_token is None:
        break

# create Google Docs file in folder
file_metadata = {
    'name': 'data.docx',
    'parents': [folder_id]
}

file = drive.files().create(body=file_metadata,
                            # media_body=media,
                            fields='id').execute()
print('File ID: %s' % file.get('id'))

【问题讨论】:

    标签: python python-3.x google-drive-api google-docs-api google-api-python-client


    【解决方案1】:

    你的情况,下面的修改怎么样?

    发件人:

    print('File ID: %s' % file.get('id'))
    

    收件人:

    print('File ID: %s' % file.get('documentId'))
    
    • 您可以通过file.get('documentId')检索创建的Google Document的文档ID。

    参考资料:

    【讨论】:

    • file.get('documentId') 返回一个文档 ID,但我在我的驱动器或谷歌文档中看不到该文档。这背后的原因是什么?如果生成了 Id,那么文档应该存在吧?
    • @Ask_Ashu 感谢您的回复。我带来的不便表示歉意。关于您的附加问题,我认为您的问题的原因是由于 Google 文档是由服务帐户创建的。服务帐户与您的 Google 帐户不同。服务帐号创建的 Document 被放到服务帐号的 Drive 中。
    • @Ask_Ashu 如果您想在 Google Drive 上查看创建的 Document,例如,首先,将您的 Google Drive 中的一个文件夹与服务帐户的电子邮件共享,并将创建的 Document 放在共享文件夹?这样,您就可以在云端硬盘上看到它。或者,如何与您的 Google 帐户共享创建的文档?您可以在stackoverflow.com/q/58080962 和stackoverflow.com/q/64626446 看到示例脚本
    • 感谢您的详细解释。现在,在授予服务帐户电子邮件对 doc 文件夹的访问权限后,我可以看到该文档。我尝试的代码已在问题中更新。
    • @Ask_Ashu 感谢您的回复。我很高兴你的问题得到了解决。也谢谢你。
    【解决方案2】:

    作为补充,@Tanaike 说,服务帐户不属于您的 Google WorkSpace 域。服务帐号创建的文件不会在您的 G Suite 域中创建。如果您想了解更多关于服务帐户与普通帐户的工作方式的信息,您可以查看Documentation。

    作为一种解决方法,您可以与用户、组、域等共享文件。改编自 Share file example:

    create_share_sa.py
    def uploadFiles():
        drive = build_service('drive', 'v3')
        new_file = drive.files().create(body={"name": "Testing"}).execute()
        # User share
        new_perm_user = {
            "type": "user",
            "role": "owner",
            "emailAddress": "your_a@domain.com",
        }
        # Domain Share
        # new_perm = {
        #     "type": "domain",
        #     "role": "reader",
        #     "domain": "domain",
        #     "allowFileDiscovery": True
        # }
        perm_id = drive.permissions().create(fileId=new_file['id'],
                                             body=new_perm_user).execute()
    
    文档

    【讨论】:

    • 我与 google 服务帐户电子邮件共享了我的文件夹,现在该文件正在创建,但是是的,我想为我的文件授予读/写权限,所以这可能会有所帮助。谢谢。
    • 很高兴听到这个消息!
    猜你喜欢
    • 1970-01-01
    • 2019-12-07
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-23
    • 1970-01-01
    • 2016-12-06
    相关资源
    最近更新 更多