【发布时间】:2022-01-21 22:41:54
【问题描述】:
在以下方法中,我尝试创建一个文档并将数据插入其中:
from googleapiclient.discovery import build
from google.oauth2 import service_account
SERVICE_FILENAME = 'C:/Users/xyz/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',
'https://www.googleapis.com/auth/documents']
)
drive = build('drive', 'v3', credentials=credentials)
docs = build('docs', 'v1', credentials=credentials)
def fetch_folder_id():
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')
return folder_id
break
page_token = response.get('nextPageToken', None)
if page_token is None:
break
def create_Doc(folder_id):
file_metadata = {
'name': 'Test.docx',
'parents': [folder_id]
}
file = drive.files().create(body=file_metadata,
fields='id').execute()
print('File ID: %s' % file.get('id'))
file_id = file.get('id')
return file_id
def grant_permissions(file_id):
try:
permission = {
"role": "writer",
"type": "user",
'emailAddress': 'xyz@gmail.com'
}
return drive.permissions().create(fileId=file_id, body=permission).execute()
except Exception as e:
print('An error occurred:', e)
return None
def insert_text(file_id):
requests = [
{
'insertText': {
'location': {
'index': 1,
},
'text': 'Hellow'
}
},
{
'insertText': {
'location': {
'index': 7,
},
'text': 'Test'
}
},
]
result = docs.documents().batchUpdate(documentId=file_id, body={'requests': requests}).execute()
print(result)
if __name__ == '__main__':
folder_id = fetch_folder_id()
file_id = create_Doc(folder_id)
grant_permissions(file_id)
insert_text(file_id)
方法:
- 使用 Drive API 获取将保存 doc 文件的
folder_id - 使用 Drive API 将父级设为
folder_id在该文件夹中创建文档 - 使用 Drive API 授予文档所需的权限
- 使用 Google Docs API 在文档中插入数据
错误: 文件正在创建中,权限也被授予,但无法在文件中插入数据。
Found file: Document_API (1xUFjYPQiDxtqdhAScUKxYdbV_gwEdAWS)
File ID: 1zasxzdaIc241raP7Ei41MRoqpg-f2sr3
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm 2021.3\plugins\python\helpers\pydev\pydevd.py", line 1483, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Program Files\JetBrains\PyCharm 2021.3\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/xyz/Test/createdoc.py", line 118, in <module>
insert_text(file_id)
File "C:/Users/xyz/Test/createdoc.py", line 110, in insert_text
result = docs.documents().batchUpdate(documentId=file_id, body={'requests': requests}).execute()
File "C:\Users\ashutosh.f.tripathi\.virtualenvs\Testpython\lib\site-packages\googleapiclient\_helpers.py", line 131, in positional_wrapper
return wrapped(*args, **kwargs)
File "C:\Users\ashutosh.f.tripathi\.virtualenvs\Testpython\lib\site-packages\googleapiclient\http.py", line 937, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://docs.googleapis.com/v1/documents/1zasxzdaIc241raP7Ei41MRoqpg-f2sr3:batchUpdate?alt=json returned "This operation is not supported for this document". Details: "This operation is not supported for this document">
python-BaseException
【问题讨论】:
-
您不是在此处创建谷歌文档。您只是将文件添加到驱动器文件夹。这可能不适用于文档 API
标签: python-3.x google-drive-api google-docs google-docs-api google-api-python-client