我正在尝试使用 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/