当我尝试使用 python 创建空白文档时,Google API 没有在驱动器中创建任何文档

Google API is not creating any document in the drive when I'm trying to create a blank document using python

我正在尝试使用以下代码生成 google 文档

    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'))

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

发件人:

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

收件人:

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

参考文献:

作为 says, service accounts do not belong to your Google WorkSpace domain. The files created by a service account are not created in your Google Workspace Domain. If you want more information on how Service Accounts work versus regular accounts, you can check the 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()
文档