import requests
from requests_toolbelt import MultipartEncoder
encoder = MultipartEncoder({'field': 'value',
'other_field', 'other_value'})
r = requests.post('https://httpbin.org/post', data=encoder,
headers={'Content-Type': encoder.content_type})
這是官方的例子,大概就是MultipartEncoder參數是一個字典,字典中存入文件名和文件內容
通常情況下,我們傳入的文件內容是open文件后的對象
這是我們公司的上傳方法
def uploadProduct(filename, binary, meta=None, area="100000"):
data = MultipartEncoder(fields={
'file': (filename, binary.getvalue(), 'text/xml'),
})
groupName = config.PRODUCT_GROUP_MAPPER[area]
rsp = requests.post('%s/%s' % (config.PRODUCT_SERVICE_URL, groupName), data=data, headers={
'Content-Type': data.content_type})
if rsp.status_code == 200:
return True, rsp.content
else:
return False, rsp.content
其中filename是需要上傳的文件名,需要注意的是,這個文件名不是文件的完整路徑,binary是文件的二進制流,”text/xml“是上傳文件的類型
然后調用上傳接口,將MultipartEncoder對象以參數的形式賦給post請求