python处理multipart/form-data的请求方法

yipeiwu_com5年前Python基础

方法1:

import requests
url = "http://www.xxxx.net/login"

#参数拼凑,附件上传格式如picurl参数,其他表单参数值拼成tuple格式:
2-tuples (filename, fileobj), 
3-tuples (filename, fileobj, contentype),
4-tuples (filename, fileobj, contentype, custom_headers)

files = {"username": (None, "billy"), "password": (None, "abcd1234"),
  'picUrl': ('pic.png', open('E:\\download\\pic.png', 'rb'), 'image/png')}

#如需headers,不需要赋值Content-Type,不然可能会报错
res = requests.post(url, files=files)
print res.request.body
print res.request.headers

方法2:

安装requests_toolbelt

pip install requests-toolbelt

实现代码

a.发送文件中的数据

from requests_toolbelt import MultipartEncoder
import requests

m = MultipartEncoder(
 fields={'field0': 'value', 'field1': 'value',
   'field2': ('filename', open('file.py', 'rb'), 'text/plain')},
 )
r = requests.post('http://httpbin.org/post', data=m,
     headers={'Content-Type': m.content_type})

b.不需要文件

from requests_toolbelt import MultipartEncoder
import requests
m = MultipartEncoder(fields={'field0': 'value', 'field1': 'value'})
r = requests.post('http://httpbin.org/post', data=m,
     headers={'Content-Type': m.content_type})

以上这篇python处理multipart/form-data的请求方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python利用pyHook实现监听用户鼠标与键盘事件

本文以一段简单的监听鼠标、键盘事件的程序,实现获取用户的输入(比如登录某些网站的账号、密码)的功能。经测试,对于一台“裸奔”的电脑,完全能获取到用户输入的任何信息;但是如果安装了杀毒软件...

在Python的Django框架中使用通用视图的方法

使用通用视图的方法是在URLconf文件中创建配置字典,然后把这些字典作为URLconf元组的第三个成员。 例如,下面是一个呈现静态“关于”页面的URLconf: from djan...

Python+OpenCV实现实时眼动追踪的示例代码

Python+OpenCV实现实时眼动追踪的示例代码

使用Python+OpenCV实现实时眼动追踪,不需要高端硬件简单摄像头即可实现,效果图如下所示。   项目演示参见:https://www.bilibili.com/vide...

Python利用itchat对微信中好友数据实现简单分析的方法

Python利用itchat对微信中好友数据实现简单分析的方法

前言 最近在一个微信公众号上看到一个调用微信 API 可以对微信好友进行简单数据分析的一个包 itchat 感觉挺好用的,就简单尝试了一下。 库文档说明链接在这: itchat 安装 在...

Tensorflow实现在训练好的模型上进行测试

Tensorflow可以使用训练好的模型对新的数据进行测试,有两种方法:第一种方法是调用模型和训练在同一个py文件中,中情况比较简单;第二种是训练过程和调用模型过程分别在两个py文件中。...