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中的并发处理之asyncio包使用的详解

导语:本文章记录了本人在学习Python基础之控制流程篇的重点知识及个人心得,打算入门Python的朋友们可以来一起学习并交流。 本文重点: 1、了解asyncio包的功能和使用方法;...

Python实现多线程HTTP下载器示例

Python实现多线程HTTP下载器示例

本文将介绍使用Python编写多线程HTTP下载器,并生成.exe可执行文件。 环境:windows/Linux + Python2.7.x 单线程 在介绍多线程之前首先介绍单线程。编写...

Python实现单词翻译功能

Python实现单词翻译功能

      在进行英文文献阅读时,经常会出现一些不认识的单词,但对于一些pdf阅读器,比如Foxit阅读器使用翻译功能需要点击(Extr...

Python3离线安装Requests模块问题

最近运维上需要在测试环境调用http的post请求,实现自动化日切,我看了下我会的编程,也就python能符合我的要求,且简单好操作。但是在实际操作过程遇到了一些问题,其中最大的就是测试...

django 自定义用户user模型的三种方法

django version: 1.7.1 最简单的推荐: 使用abstractuser扩充fields 复制代码 代码如下: profiles/models.py from djang...