本篇內(nèi)容介紹了“python MultipartEncoder如何傳輸zip文件”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!

Python是一種編程語言,內(nèi)置了許多有效的工具,Python幾乎無所不能,該語言通俗易懂、容易入門、功能強大,在許多領(lǐng)域中都有廣泛的應用,例如最熱門的大數(shù)據(jù)分析,人工智能,Web開發(fā)等。
需求:對方提供處理文件的接口,本地將待處理文件壓縮后,通過http post multipart方式上傳,等待處理完成后從相應連接下載結(jié)果
代碼:
import os
import time
import zipfile
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
class Func4Fuxi(object):
def __init__(self):
self.remote_result = 0
# 壓縮文件
def zip_dir(self, dirname, zipfilename):
filelist = []
if os.path.isfile(dirname):
filelist.append(dirname)
else:
for root, dirs, files in os.walk(dirname):
for name in files:
filelist.append(os.path.join(root, name))
zf = zipfile.ZipFile(zipfilename, mode="w", compression=zipfile.zlib.DEFLATED, allowZip64=True)
for tar in filelist:
arcname = tar[len(dirname):]
zf.write(tar, arcname)
zf.close()
# 解壓文件
def unzip_file(self, zipfilename, unziptodir):
if not os.path.exists(unziptodir):
os.mkdir(unziptodir)
zfobj = zipfile.ZipFile(zipfilename)
for name in zfobj.namelist():
name = name.replace('\\', '/')
if name.endswith('/'):
os.mkdir(os.path.join(unziptodir, name))
else:
ext_filename = os.path.join(unziptodir, name)
ext_dir = os.path.dirname(ext_filename)
if not os.path.exists(ext_dir):
os.mkdir(ext_dir)
outfile = open(ext_filename, 'wb')
outfile.write(zfobj.read(name))
outfile.close()
# 下載
def download_result(self, filename):
filename.replace('\\', '/')
file = filename.split('/')[-1]
URL = '--------------'
re = requests.get(URL+'?name='+file, stream=True)
self.remote_result = re.status_code
if self.remote_result == 200:
print("find result,try to download")
f = open("download_"+file, "wb")
for chunk in re.iter_content(chunk_size=512):
if chunk:
f.write(chunk)
print("download result success")
return self.remote_result
# 上傳
def upload_zip(self, filename):
self.remote_result = 0
filename.replace('\\', '/')
file = filename.split('/')[-1]
file_tup = (file, open(filename, 'rb'), 'application/zip')
URL = '-----------------'
#fields屬性根據(jù)對方接口說明設(shè)置
m = MultipartEncoder(
fields={'name': file, 'zipfile': file_tup}
)
re = requests.post(URL, data=m, headers={'Content-Type': m.content_type})
self.remote_result = re.status_code
if self.remote_result == 200:
print("upload success")
else:
print("upload failed")
return self.remote_result補充知識:Python模擬瀏覽器上傳文件腳本(Multipart/form-data格式)
http協(xié)議本身的原始方法不支持multipart/form-data請求,這個請求由原始方法演變而來的。
multipart/form-data的基礎(chǔ)方法是post,也就是說是由post方法來組合實現(xiàn)的,與post方法的不同之處:請求頭,請求體。
multipart/form-data的請求頭必須包含一個特殊的頭信息:
Content-Type,且其值也必須規(guī)定為multipart/form-data,同時還需要規(guī)定一個內(nèi)容分割符用于分割請求體中的多個post的內(nèi)容,如文件內(nèi)容和文本內(nèi)容自然需要分割開來,不然接收方就無法正常解析和還原這個文件了。
具體的頭信息如下:
Content-Type: multipart/form-data; boundary=${bound}
實例:
import os, random, sys, requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
url = 'http://127.0.0.1/sendmsg'
argvstr = sys.argv[1:]
argv_dict = {}
for argv in argvstr :
argv = str(argv).replace("\r\n" , "")
DICT = eval(argv)
argv_dict.update(DICT)
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0',
'Referer': url
}
multipart_encoder = MultipartEncoder(
fields={
'username': argv_dict['username'],
'pwd': argv_dict['pwd'],
'type': 'txt',
'friendfield': argv_dict['friendfield'],
'friend': argv_dict['friend'],
'content': argv_dict['content'],
'file': (os.path.basename(argv_dict['file']) , open(argv_dict['file'], 'rb'), 'application/octet-stream')
#file為路徑
},
boundary='-----------------------------' + str(random.randint(1e28, 1e29 - 1))
)
headers['Content-Type'] = multipart_encoder.content_type
#請求頭必須包含一個特殊的頭信息,類似于Content-Type: multipart/form-data; boundary=${bound}
r = requests.post(url, data=multipart_encoder, headers=headers)
print(r.text)
#注意,不要設(shè)置cookies等其他參數(shù),否則會報錯
# 例子/usr/local/python36/bin/python3 /opt/lykchat/test_upload.py "{'username':'lykchat','pwd':'123456','type':'img','friendfield':'1','friend':'xxxx','content':'恭喜發(fā)財','file':'/root/b.jpg'}"
#等同于curl -F "file=@/root/a" 'http://127.0.0.1/sendmsg?username=lykchat&pwd=123456&type=img&friendfield=1&friend=xxxx&content=恭喜發(fā)財'“python MultipartEncoder如何傳輸zip文件”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!
當前題目:pythonMultipartEncoder如何傳輸zip文件-創(chuàng)新互聯(lián)
瀏覽地址:http://chinadenli.net/article12/eoggc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)建站、網(wǎng)站收錄、網(wǎng)站內(nèi)鏈、響應式網(wǎng)站、網(wǎng)站營銷、網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容