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

yipeiwu_com6年前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中的日期时间处理详解

Python中的日期时间处理详解

Python中关于时间、日期的处理库有三个:time、datetime和Calendar,其中datetime又有datetime.date、datetime.time、datetime...

浅谈Django自定义模板标签template_tags的用处

浅谈Django自定义模板标签template_tags的用处

自定义模板标签,过滤器。英文翻译是Customtemplatetagsandfilters。customfilter自定义过滤器今天不在我的记录范围之内,以后用到再看官方文档也不迟。 *...

Python 稀疏矩阵-sparse 存储和转换

Python 稀疏矩阵-sparse 存储和转换

稀疏矩阵-sparsep from scipy import sparse 稀疏矩阵的储存形式 在科学与工程领域中求解线性模型时经常出现许多大型的矩阵,这些矩阵中大部分的元素都为0...

Python中logging.NullHandler 的使用教程

在使用 peewee 框架时,默认是不会出现日志消息的。 from peewee import Model, CharField, DateTimeField, IntegerFie...

python赋值操作方法分享

一、序列赋值: x,y,z = 1,2,3 我们可以看作:x = 1,y = 2,z = 3 二、链接赋值: x = y = 1print id(x)print id(y) 大家可以看下...