gpt4 book ai didi

python - Google Client API v3 - 使用 Python 更新驱动器上的文件

转载 作者:太空宇宙 更新时间:2023-11-03 21:26:03 25 4
gpt4 key购买 nike

我正在尝试使用 google 客户端 API 从 python 脚本更新文件的内容。问题是我不断收到错误 403:

An error occurred: <HttpError 403 when requesting https://www.googleapis.com /upload/drive/v3/files/...?alt=json&uploadType=resumable returned "The resource body includes fields which are not directly writable.

我尝试删除元数据字段,但没有帮助。

更新文件的函数如下:

# File: utilities.py
from googleapiclient import errors
from googleapiclient.http import MediaFileUpload
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

def update_file(service, file_id, new_name, new_description, new_mime_type,
new_filename):
"""Update an existing file's metadata and content.

Args:
service: Drive API service instance.
file_id: ID of the file to update.
new_name: New name for the file.
new_description: New description for the file.
new_mime_type: New MIME type for the file.
new_filename: Filename of the new content to upload.
new_revision: Whether or not to create a new revision for this file.
Returns:
Updated file metadata if successful, None otherwise.
"""
try:
# First retrieve the file from the API.
file = service.files().get(fileId=file_id).execute()

# File's new metadata.
file['name'] = new_name
file['description'] = new_description
file['mimeType'] = new_mime_type
file['trashed'] = True

# File's new content.
media_body = MediaFileUpload(
new_filename, mimetype=new_mime_type, resumable=True)

# Send the request to the API.
updated_file = service.files().update(
fileId=file_id,
body=file,
media_body=media_body).execute()
return updated_file
except errors.HttpError as error:
print('An error occurred: %s' % error)
return None

这里有重现问题的完整脚本。目标是替换文件,通过名称检索其 id。如果该文件尚不存在,脚本将通过调用 insert_file 创建它(此函数按预期工作)。问题是上面发布的 update_file

from __future__ import print_function
from utilities import *
from googleapiclient import errors
from googleapiclient.http import MediaFileUpload
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

def get_authenticated(SCOPES, credential_file='credentials.json',
token_file='token.json', service_name='drive',
api_version='v3'):
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
store = file.Storage(token_file)
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets(credential_file, SCOPES)
creds = tools.run_flow(flow, store)
service = build(service_name, api_version, http=creds.authorize(Http()))
return service


def retrieve_all_files(service):
"""Retrieve a list of File resources.

Args:
service: Drive API service instance.
Returns:
List of File resources.
"""

result = []
page_token = None
while True:
try:
param = {}
if page_token:
param['pageToken'] = page_token
files = service.files().list(**param).execute()

result.extend(files['files'])
page_token = files.get('nextPageToken')
if not page_token:
break
except errors.HttpError as error:
print('An error occurred: %s' % error)
break

return result


def insert_file(service, name, description, parent_id, mime_type, filename):
"""Insert new file.

Args:
service: Drive API service instance.
name: Name of the file to insert, including the extension.
description: Description of the file to insert.
parent_id: Parent folder's ID.
mime_type: MIME type of the file to insert.
filename: Filename of the file to insert.
Returns:
Inserted file metadata if successful, None otherwise.
"""
media_body = MediaFileUpload(filename, mimetype=mime_type, resumable=True)
body = {
'name': name,
'description': description,
'mimeType': mime_type
}
# Set the parent folder.
if parent_id:
body['parents'] = [{'id': parent_id}]

try:
file = service.files().create(
body=body,
media_body=media_body).execute()

# Uncomment the following line to print the File ID
# print 'File ID: %s' % file['id']

return file
except errors.HttpError as error:
print('An error occurred: %s' % error)
return None


# If modifying these scopes, delete the file token.json.
SCOPES = 'https://www.googleapis.com/auth/drive'

def main():
service = get_authenticated(SCOPES)

# Call the Drive v3 API
results = retrieve_all_files(service)

target_file_descr = 'Description of deploy.py'
target_file = 'deploy.py'
target_file_name = target_file
target_file_id = [file['id'] for file in results if file['name'] == target_file_name]

if len(target_file_id) == 0:
print('No file called %s found in root. Create it:' % target_file_name)
file_uploaded = insert_file(service, target_file_name, target_file_descr, None,
'text/x-script.phyton', target_file_name)
else:
print('File called %s found. Update it:' % target_file_name)
file_uploaded = update_file(service, target_file_id[0], target_file_name, target_file_descr,
'text/x-script.phyton', target_file_name)

print(str(file_uploaded))


if __name__ == '__main__':
main()

为了尝试该示例,需要从 https://console.developers.google.com/apis/dashboard 创建 Google Drive API ,然后保存文件 credentials.js 并将其路径传递给 get_authenticated()。文件 token.json 将在第一个之后创建身份验证和API授权。

最佳答案

问题是元数据“id”在更新文件时无法更改,因此它不应该出现在正文中。只需从字典中删除它即可:

# File's new metadata.
del file['id'] # 'id' has to be deleted
file['name'] = new_name
file['description'] = new_description
file['mimeType'] = new_mime_type
file['trashed'] = True

我尝试了您的代码并进行了此修改,它有效

关于python - Google Client API v3 - 使用 Python 更新驱动器上的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53831492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com