![](/img/trans.png)
[英]Python Google drive API cannot insert media file using mediaFileUpload
[英]Google Drive API Python insert file
我正在嘗試使用Python 2.7將png文件加載到Google雲端硬盤。 該文件的Google Drive API Quickstart.py正常運行。 MyTestFile.png文件與我使用的Python腳本位於同一目錄中。
我不確定100%是否使用了正確的服務,但這就是Quickstart.py附帶的內容
錯誤消息是:AttributeError:'資源'對象沒有屬性'插入'
from __future__ import print_function
import httplib2
import os
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from apiclient import errors
from apiclient.http import MediaFileUpload
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/drive-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/drive'
CLIENT_SECRET_FILE = 'Google_Drive_API_Stock_Selection_020218_client_id.json'
APPLICATION_NAME = 'Drive API Python Insert File'
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'drive-python-quickstart.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def main():
"""Writes file to Google Drive
"""
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('drive', 'v3', http=http)
filename = 'MyTestFile_A.png'
title = '"title": "MyTestFile_A.png"'
description = 'Test Image'
mime_type = 'image/png'
parent_id = ' '
insert_file(service, title, description, parent_id, mime_type, filename)
def insert_file(service, title, description, parent_id, mime_type, filename):
"""Insert new file.
Args:
service: Drive API service instance.
title: Title 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 = {
'title': title,
'description': description,
'mimeType': mime_type
}
# Set the parent folder.
if parent_id:
body['parents'] = [{'id': parent_id}]
try:
file = service.files().insert(
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, error:
print ('An error occurred: %s' % error )
return None
if __name__ == '__main__':
main()
這意味着您使用的驅動器API版本錯誤。 files.insert
僅適用於Drive API V2。 您可以使用files.create
作為替代,因為Drive API V3當前使用了它。 有關更多的見解和示例代碼,請參考文檔 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.