代码之家  ›  专栏  ›  技术社区  ›  Buju

通过Google Drive REST API使用httplib2上传文件/元数据

  •  1
  • Buju  · 技术社区  · 9 年前

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

    我得出的结论是,httplib2不支持多部分上传,除非我自己为其编写逻辑,所以我将方法分为两部分来上传元数据和上传文件内容。

    #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):创建的文档标题为“无标题”,无描述。我是否为uploadMeta函数设置了错误的正文或标题格式?

    1 回复  |  直到 9 年前
        1
  •  0
  •   Buju    9 年前

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

    body = json.dumps(post_data)
    

    但这不适用于发送文件内容。我还在琢磨如何发送文件。

    编辑 :我改为使用 Requests 进行http请求,并设法使用来自的解决方案同时上传文档和元数据 this exchange .