【问题标题】:Python request for Google Drive对 Google Drive 的 Python 请求
【发布时间】:2014-05-11 15:32:30
【问题描述】:

我正在尝试使用 python 请求库将文件发送到 Google Drive api。根据谷歌文档,我唯一需要它来发送多部分请求 https://developers.google.com/drive/web/manage-uploads#multipart 我需要先发送元数据,然后再发送文件。这是我到目前为止所尝试的

    def upload_csv(self, file, description):
      self.refresh()
      url = self.url+'?uploadType=multipart&' + urllib.urlencode({'key':self.api_key})

      headers = { 'Authorization':'Bearer {}'.format(self.access_token),
    #                    'content-type':'multipart/related',
    #                    'content-length':size
                }

      data =  {'title':file,'description':description }
      files = {'file':(file,open(file,'rb'),'text/csv')}
      response = requests.post( url, headers = headers, data = data, files = files )

但我得到一个错误:u'Bad content type。请使用多部分。 有没有办法使用请求发送元数据和文件

【问题讨论】:

标签: python google-api python-requests


【解决方案1】:

我想出了一个办法。问题是谷歌想要元数据和文件在一起。

    def upload_csv(self, file, description):
      self.refresh()
      url = self.url+'?uploadType=multipart&convert=true' +   urllib.urlencode({'key':self.api_key})

      headers = { 'Authorization':'Bearer {}'.format(self.access_token) }

      class DataDict(dict):
          def read(self):
              return str( self )

      data = ('metadata',DataDict(title = file,description = description),'application/json; charset=UTF-8')
      file = (file,open(file,'rb'),'text/csv')
      files = {'data':data, 'file':file }
      response = requests.post( url, headers = headers, files = files )
      return respone

【讨论】:

  • 你在间接产生 JSON;只需使用 json 模块来生成元数据条目。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-02
  • 1970-01-01
  • 1970-01-01
  • 2012-11-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多