concall,havd-686,ok网
方法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 实现将numpy中的nan和inf,nan替换成对应的均值
python爬虫把url链接编码成gbk2312格式过程解析
网友评论