通过 Google Drive REST API 使用 httplib2 上传 file/metadata

Uploading file/metadata with httplib2 via Google Drive REST API

我正在尝试编写一个与 Google Drive REST API[1] 交互的简单 CRUD 库。我可以从我的驱动器中获取和删除,但我在上传文件时遇到问题。

我得出的结论是 httplib2 不支持 multi-part 上传,但我没有为它编写自己的逻辑,所以我将这些方法分成两部分来上传元数据和上传文件内容。

#ToDo: needs to be fixed to send binary data correctly, maybe set mimetype
#ToDo: add file metadata via second request (multipart not supported by httplib2)
def uploadDoc(self, filename, fileid=None):
    #ToDo: detect filetype
    data_type = 'image/png'
    # content_length //automatically detected
    url = "https://www.googleapis.com/upload/drive/v2/files"
    method = "POST"
    #replace file at this id if updating file
    if fileid:
        url += "/" + fileid
        method = "PUT"

    headers = {'Authorization' : 'Bearer ' + self.getTokenFromFile(), 'Content-type' : data_type}
    post_data = {'uploadType':'media',
                'file' :self.load_binary(filename)}

    (resp, content) = self.http.request(url,
                            method = method,
                            body = urlencode(post_data),
                            headers = headers)

    print content

#ToDo: metadata not being set, including content-type in header returns 400 status
def uploadFileMeta(self, filename, fileid=None, description=""):
    url = self.drive_api_url + "/files" 
    method = "POST"
    #replace file metadata at this id if updating file
    if fileid:
        url += "/" + fileid
        method = "PUT"

    headers = {'Authorization' : 'Bearer ' + self.getTokenFromFile()}
    post_data = {"title" : filename,
                "description": description}

    (resp, content) = self.http.request(url,
                            method = method,
                            body = urlencode(post_data),
                            headers = headers)

    print resp
    print content

#updating a specific doc will require the fileid
def updateFileMeta(self, fileid, filename, description=""):
    uploadFileMeta(fileid, filename, description)

def reuploadFile(self, fileid, filename):
    uploadDoc(filename, fileid)

def load_binary(self, filename):
    with open(filename, 'rb') as f:
        return f.read()

当我尝试设置标题或描述时,标题设置为 "Untitled" 并且描述根本不显示在返回的 JSON 中。好像我没有将它们正确发送到服务器。

我的另一个问题是上传二进制文件。我相信我正在读取文件或编码不正确。

如有任何建议,我们将不胜感激。几个星期以来,我一直在摸不着头脑。

谢谢!

编辑: 澄清(TLDR):创建的文档标题为:"Untitled",没有描述。我是否为 uploadMeta 函数错误地格式化了 body 或 headers?

我需要按照 Gerardo 建议的元数据在我的请求中发送 json。

body = json.dumps(post_data)

虽然这不适用于发送文件内容。还在为如何发送文件而绞尽脑汁。

编辑:我切换到使用Requests to make the http requests and have managed to upload docs and metadata at the same time using the solution from this exchange