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实现代码,供大家参考,具体内容如下 有一组源数据,第一行会是个日期数据,第二行标明字段,再接下来是两行数据行。 1018 14:3...

Python简明入门教程

本文实例讲述了Python简明入门教程。分享给大家供大家参考。具体如下: 一、基本概念 1、数 在Python中有4种类型的数——整数、长整数、浮点数和复数。 (1)2是一个整数的例子。...

利用Python脚本生成sitemap.xml的实现方法

安装lxml 首先需要pip install lxml安装lxml库。 如果你在ubuntu上遇到了以下错误: #include "libxml/xmlversion.h" co...

python消费kafka数据批量插入到es的方法

1、es的批量插入 这是为了方便后期配置的更改,把配置信息放在logging.conf中 用elasticsearch来实现批量操作,先安装依赖包,sudo pip install El...

python自带的http模块详解

挺久没写博客了,因为博主开始了今年另一段美好的实习经历,学习加做项目,时间已排满;很感谢今年这两段经历,让我接触了golang和python,学习不同语言,可以跳出之前学习c/c++思维...