对 Google 云端硬盘的 Python 请求

标签 python google-api python-requests

我正在尝试使用 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。请使用多部分。 有没有办法使用请求发送元数据和文件

最佳答案

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

    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

关于对 Google 云端硬盘的 Python 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23594515/

相关文章:

google-analytics - 如何在 Google Analytics 中获取我的 Profile-ID 的每日配额中剩余的请求数

c# - 如何使用 C# 对 Picasa 网络相册数据 API 进行 OAuth2 身份验证?

python - PyPy:导入错误:没有名为请求的模块

python - 如何使用Python Request实现ajax请求

Python:从字典中获取具有最小值但有多个最小值的键

python - 如何配置 Django 访问远程 MySQL db django.contrib.sites.RequestSite 模块缺失

python - 在 Python 的 numpy 中,当我要设置的值位于不同大小的数组中时,如何有条件地重写数组的一部分?

java - 异常 : 401 Unauthorized Error | com. google.api.client.auth.oauth2.TokenResponseException:401 未经授权

python flask : Send file and variable

python - 如何仅对没有扩展名的文件进行 glob?