Google Drive API Python插入文件

时间:2018-02-18 21:15:00

标签: python google-drive-api

我正在尝试使用Python 2.7将png文件加载到Google云端硬盘。该文件的Google Drive API Quickstart.py正常运行。文件MyTestFile.png与我正在使用的Python脚本位于同一目录中。

我并非100%确定我使用的是正确的服务,但这是Quickstart.py附带的内容

错误消息为:AttributeError:'Resource'对象没有属性'insert'

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

1 个答案:

答案 0 :(得分:0)

这表示您使用的是错误版本的Drive API调用。 files.insert仅适用于Drive API V2。您可以使用files.create作为替代品,因为目前在Drive API V3中使用了此功能。有关更多见解和示例代码,请参阅Documentation