python使用request发送post请求_python3使用request来post文件请求

最近尝试使用request来发送上传文件的post请求,网上找了很多直接post文件的例子,借鉴发现这个方法行不通,于是尝试了另外一种方式:通过第三方包requests_toolbelt讲文件转为数据流来发送请求,尝试成功。

第一类,单个文件,包含在消息体

# -*- coding: utf-8 -*-

import requests

#引入requests_toolbelt包,直接使用数据流来发送上传文件的post请求

from requests_toolbelt.multipart.encoder import MultipartEncoder

url = "http://host/test/bTutorCircle/uploadFile"

m=MultipartEncoder(fields = {

"account":"qatest@chaozhi1v1.com",

"metaTag":"TOPIC_IMAGE",

'file':('12.jpg',open('C:\\Users\\Desktop\\test_img\\12.jpg', 'rb'),'application/jpg')

})

headers = {

'Accept-Encoding': "gzip, deflate",

'Content-Type': m.content_type,

}

response = requests.request("POST", url, data=m, headers=headers)

print(response.text)

第二类,多个文件,参数复杂组合情况

# -*- coding: utf-8 -*-

import requests

#引入requests_toolbelt包,直接使用数据流来发送上传文件的post请求

from requests_toolbelt.multipart.encoder import MultipartEncoder

url = "http://host/test/content/inserOrUpdate?token=11E5F02EC251CCBFDBAF0BEE3B23DF35"

m=MultipartEncoder(fields = {

"trainContent":str({"title":"tet","introduction":"

test

","videoLinkType":1,"videoUrl":"","videoDurationM":"2","videoDurationS":0,"videoDuration":120}),

"ppt":('12.jpg',open('C:\\Users\\Desktop\\test_img\\12.jpg', 'rb'),'application/jpg'),

'cover':('12.jpg',open('C:\\Users\\Desktop\\test_img\\12.jpg', 'rb'),'application/jpg'),

'video':('12.jpg',open('C:\\Users\\Desktop\\test_img\\12.jpg', 'rb'),'application/jpg')

})

headers = {

'Accept-Encoding': "gzip, deflate",

'Content-Type': m.content_type,

}

response = requests.request("POST", url, data=m, headers=headers)

print(response.text)

附件文件支持多种文件,比如ppt,xls,jmx等等,把对应字符替换即可。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值