3

我想编写一个脚本将我的照片上传到 Google Drive。经过几个小时深入研究 Google Document List API。我选择 gdata-python-client 2.0.17(latest) 来构建我的脚本。一切正常,除了我无法将文件上传到集合中。这是例外。

回溯(最近一次通话最后):
  文件“./upload.py”,第 27 行,在
    上传(sys.argv[1])
  文件“./upload.py”,第 22 行,上传中
    client.create_resource(p, collection=f, media=ms)
  文件“/usr/local/lib/python2.7/dist-packages/gdata/docs/client.py”,第 300 行,在 create_resource
    return uploader.upload_file(create_uri, entry, **kwargs)
  文件“/usr/local/lib/python2.7/dist-packages/gdata/client.py”,第 1090 行,在 upload_file
    start_byte, self.file_handle.read(self.chunk_size))
  文件“/usr/local/lib/python2.7/dist-packages/gdata/client.py”,第 1048 行,在 upload_chunk
    引发错误
gdata.client.RequestError:服务器响应:400,<errors xmlns='http://schemas.google.com/g/2005'><error><domain>GData</domain><code>InvalidEntryException</code ><internalReason>很抱歉,发生服务器错误。请重试。</internalReason></error></errors>

在侵入 gdata 的源代码后,我打印了一些信息以进行调试。

>
范围:字节 0-524287/729223
放入:https://docs.google.com/feeds/upload/create-session/default/private/full/folder%3A0B96cfHivZx6ddGFwYXVCbzc4U3M/contents?upload_id=AEnB2UqnYRFTOyCCIGIESUIctWg6hvQIHY4JRMnL-CUQhHii3RGMFWZ12a7lXWd1hgOChd1Vqlr8dVnwh-B
>
范围:字节 524288-729222/729223
放入:https://docs.google.com/feeds/upload/create-session/default/private/full/folder%3A0B96cfHivZx6ddGFwYXVCbzc4U3M/contents?upload_id=AEnB2UqnYRFTOyCCIGIESUIctWg6hvQIHY4JRMnL-CUQhHii3RGMFWZ12a7lXWd1hgOChd1Vqlr8dVnwh-B

PUT文件的最后一部分时引发的异常。

4

1 回答 1

1

我建议您尝试新的 Google Drive API v2,它通过更好地支持媒体上传使其变得更加容易:https ://developers.google.com/drive/v2/reference/files/insert

获得授权服务实例后,您可以简单地插入一个新文件,如下所示:

from apiclient import errors
from apiclient.http import MediaFileUpload
# ...

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

    return file
  except errors.HttpError, error:
    print 'An error occured: %s' % error
    return None
于 2012-07-10T16:40:24.757 回答