如何解决"属性错误:'Resource'对象没有属性'文档'"错误?



我在这最后3天工作。我不知道……有类似的问题,但我没有得到我的答案。

this is ERROR

文件ID: 1U4XUrAhMk1WFAKE_IDqmQcteYqmIWPMFEd Traceback(最近的)

我想使用这个ID并在驱动器中编辑文档

call last): File "main.py",第61行,

main()   File "main.py", line 53, in main
service.documents() AttributeError: 'Resource' object has no attribute 'documents'

我的目标

  1. create Docs in GOOGLE Drive

  2. insert Table in it

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 sys
from gdoctableapppy import gdoctableapp
# If modifying these scopes, delete the file token.pickle.
SCOPES = ["https://www.googleapis.com/auth/drive"]

def main():
"""Shows basic usage of the Drive v3 API.
Prints the names and ids of the first 10 files the user has access to.
"""
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("drive", "v3", credentials=creds)
serviceDoc = build("docs", "v1", credentials=creds)
# Call the Drive v3 API
# Create Google Docs file in folder
file_metadata = {
"name": sys.argv[1],
"parents": ["Folder ID"],
}
file = service.files().create(body=file_metadata, fields="id").execute()
print("File ID: %s" % file.get("id"))
DOCUMENT_ID = file.get("id")
requests = [{"insertTable": {"rows": 2, "columns": 2, "location": {"index": 1}}}]
result = (
service.documents()
.batchUpdate(documentId=DOCUMENT_ID, body={"requests": requests})
.execute()
)
return
if __name__ == "__main__":
main()

你遇到这样的错误的原因是因为你的service变量是驱动器API,它没有documents()方法。

serviceDoc代替

serviceDoc.documents()
.batchUpdate(documentId=DOCUMENT_ID, body={"requests": requests})
.execute()
除了:

我注意到,当你创建一个Docs文件mimeType不是你的file_metadata的一部分。如果您创建的文件没有特定的mimeType,则新创建的文件将是application/octet-stream。参见创建文件

如果你想使用Drive API创建Google Docs,请在你的file_metadata中添加"mimeType"='application/vnd.google-apps.document'

示例:

file_metadata = {
"name": sys.argv[1],
"mimeType"='application/vnd.google-apps.document',
"parents": ["Folder ID"]
}

参考:

  • Google Workspace and Drive MIME Types

最新更新