尝试将图像文件上载到集合时出现400错误

时间:2012-07-10 13:17:22

标签: python google-drive-api

我想写一个脚本将我的照片上传到Google云端硬盘。经过几个小时的挖掘Google Document List API。我选择gdata-python-client 2.0.17(最新版)来构建我的脚本。一切都运作良好,除了我无法将文件上传到集合。这是例外。

Traceback (most recent call last):
  File "./upload.py", line 27, in 
    upload(sys.argv[1])
  File "./upload.py", line 22, in upload
    client.create_resource(p, collection=f, media=ms)
  File "/usr/local/lib/python2.7/dist-packages/gdata/docs/client.py", line 300, in create_resource
    return uploader.upload_file(create_uri, entry, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/gdata/client.py", line 1090, in upload_file
    start_byte, self.file_handle.read(self.chunk_size))
  File "/usr/local/lib/python2.7/dist-packages/gdata/client.py", line 1048, in upload_chunk
    raise error
gdata.client.RequestError: Server responded with: 400, <errors xmlns='http://schemas.google.com/g/2005'><error><domain>GData</domain><code>InvalidEntryException</code><internalReason>We're sorry, a server error occurred. Please try again.</internalReason></error></errors>

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

>
Range: bytes 0-524287/729223
PUT TO: https://docs.google.com/feeds/upload/create-session/default/private/full/folder%3A0B96cfHivZx6ddGFwYXVCbzc4U3M/contents?upload_id=AEnB2UqnYRFTOyCCIGIESUIctWg6hvQIHY4JRMnL-CUQhHii3RGMFWZ12a7lXWd1hgOChd1Vqlr8d-BmvyfmhFhzhYK9Vnw4Xw
>
Range: bytes 524288-729222/729223
PUT TO: https://docs.google.com/feeds/upload/create-session/default/private/full/folder%3A0B96cfHivZx6ddGFwYXVCbzc4U3M/contents?upload_id=AEnB2UqnYRFTOyCCIGIESUIctWg6hvQIHY4JRMnL-CUQhHii3RGMFWZ12a7lXWd1hgOChd1Vqlr8d-BmvyfmhFhzhYK9Vnw4Xw

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

1 个答案:

答案 0 :(得分:1)

我建议您尝试使用新的Google Drive API v2,以便更好地支持媒体上传:https://developers.google.com/drive/v2/reference/files/insert

获得authorized service instance后,您只需插入一个新文件:

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