python處理multipart/form-data的請求方法
方法1:
import requests
url = "http://www.xxxx.net/login"
#參數(shù)拼湊,附件上傳格式如picurl參數(shù),其他表單參數(shù)值拼成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
實現(xiàn)代碼
a.發(fā)送文件中的數(shù)據(jù)
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的請求方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python 申請內(nèi)存空間,用于創(chuàng)建多維數(shù)組的實例
今天小編就為大家分享一篇python 申請內(nèi)存空間,用于創(chuàng)建多維數(shù)組的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
Pycharm創(chuàng)建項目時如何自動添加頭部信息
這篇文章主要介紹了Pycharm創(chuàng)建項目時 自動添加頭部信息,需要的朋友可以參考下2019-11-11
TorchVision Transforms API目標(biāo)檢測實例語義分割視頻類
這篇文章主要為大家介紹了TorchVision Transforms API大升級,支持目標(biāo)檢測、實例/語義分割及視頻類任務(wù)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11
python 中pyqt5 樹節(jié)點點擊實現(xiàn)多窗口切換問題
這篇文章主要介紹了python 中pyqt5 樹節(jié)點點擊實現(xiàn)多窗口切換問題,文中給大家介紹了python pyqt5 點擊按鈕來打開另一個窗口的方法,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒借鑒價值,需要的朋友可以參考下2019-07-07
python學(xué)習(xí)之hook鉤子的原理和使用
這篇文章主要為大家詳細介紹了python學(xué)習(xí)之hook鉤子的原理和使用,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-10-10

