亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

python MultipartEncoder傳輸zip文件實(shí)例

 更新時(shí)間:2020年04月07日 16:42:10   作者:Showjy  
這篇文章主要介紹了python MultipartEncoder傳輸zip文件實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

需求:對(duì)方提供處理文件的接口,本地將待處理文件壓縮后,通過(guò)http post multipart方式上傳,等待處理完成后從相應(yīng)連接下載結(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ù)對(duì)方接口說(shuō)明設(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

補(bǔ)充知識(shí):Python模擬瀏覽器上傳文件腳本(Multipart/form-data格式)

http協(xié)議本身的原始方法不支持multipart/form-data請(qǐng)求,這個(gè)請(qǐng)求由原始方法演變而來(lái)的。

multipart/form-data的基礎(chǔ)方法是post,也就是說(shuō)是由post方法來(lái)組合實(shí)現(xiàn)的,與post方法的不同之處:請(qǐng)求頭,請(qǐng)求體。

multipart/form-data的請(qǐng)求頭必須包含一個(gè)特殊的頭信息:

Content-Type,且其值也必須規(guī)定為multipart/form-data,同時(shí)還需要規(guī)定一個(gè)內(nèi)容分割符用于分割請(qǐng)求體中的多個(gè)post的內(nèi)容,如文件內(nèi)容和文本內(nèi)容自然需要分割開(kāi)來(lái),不然接收方就無(wú)法正常解析和還原這個(gè)文件了。

具體的頭信息如下:

Content-Type: multipart/form-data; boundary=${bound}

實(shí)例:

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
#請(qǐng)求頭必須包含一個(gè)特殊的頭信息,類似于Content-Type: multipart/form-data; boundary=${bound}
 
r = requests.post(url, data=multipart_encoder, headers=headers)
print(r.text)
#注意,不要設(shè)置cookies等其他參數(shù),否則會(huì)報(bào)錯(cuò)
 
# 例子/usr/local/python36/bin/python3 /opt/lykchat/test_upload.py "{'username':'lykchat','pwd':'123456','type':'img','friendfield':'1','friend':'xxxx','content':'恭喜發(fā)財(cái)','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ā)財(cái)'

以上這篇python MultipartEncoder傳輸zip文件實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python使用matplotlib繪制動(dòng)畫(huà)的方法

    Python使用matplotlib繪制動(dòng)畫(huà)的方法

    這篇文章主要介紹了Python使用matplotlib繪制動(dòng)畫(huà)的方法,涉及matplotlib模塊的常見(jiàn)使用技巧,需要的朋友可以參考下
    2015-05-05
  • 10個(gè)python爬蟲(chóng)入門基礎(chǔ)代碼實(shí)例 + 1個(gè)簡(jiǎn)單的python爬蟲(chóng)完整實(shí)例

    10個(gè)python爬蟲(chóng)入門基礎(chǔ)代碼實(shí)例 + 1個(gè)簡(jiǎn)單的python爬蟲(chóng)完整實(shí)例

    這篇文章主要介紹了10個(gè)python爬蟲(chóng)入門基礎(chǔ)代碼實(shí)例和1個(gè)簡(jiǎn)單的python爬蟲(chóng)爬蟲(chóng)貼吧圖片的實(shí)例,需要的朋友可以參考下
    2020-12-12
  • Python的matplotlib繪圖如何修改背景顏色的實(shí)現(xiàn)

    Python的matplotlib繪圖如何修改背景顏色的實(shí)現(xiàn)

    這篇文章主要介紹了Python的matplotlib繪圖如何修改背景顏色的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-07-07
  • 分享幾道你可能遇到的python面試題

    分享幾道你可能遇到的python面試題

    最近去筆試,在面試過(guò)程中遇到了幾個(gè)編程題,比較基礎(chǔ)。所以想著總結(jié)一下,所以下面這篇文章主要給大家分享了幾道你可能遇到的python面試題,文中給出了詳細(xì)的示例代碼供大家參考學(xué)習(xí),需要的朋友們下面來(lái)一起看看吧。
    2017-07-07
  • python根據(jù)txt文本批量創(chuàng)建文件夾

    python根據(jù)txt文本批量創(chuàng)建文件夾

    這篇文章主要為大家詳細(xì)介紹了python根據(jù)txt文本批量創(chuàng)建文件夾,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-03-03
  • 深入淺析python with語(yǔ)句簡(jiǎn)介

    深入淺析python with語(yǔ)句簡(jiǎn)介

    with 語(yǔ)句適用于對(duì)資源進(jìn)行訪問(wèn)的場(chǎng)合,確保不管使用過(guò)程中是否發(fā)生異常都會(huì)執(zhí)行必要的“清理”操作,釋放資源,這篇文章給大家介紹了python with語(yǔ)句簡(jiǎn)介,感興趣的朋友一起看看吧
    2018-04-04
  • Python真題案例之二分法查找詳解

    Python真題案例之二分法查找詳解

    這篇文章主要介紹了python實(shí)操案例練習(xí),本文給大家分享的案例中主要講解了二分法查找,需要的小伙伴可以參考一下
    2022-03-03
  • Tensorflow與Keras自適應(yīng)使用顯存方式

    Tensorflow與Keras自適應(yīng)使用顯存方式

    這篇文章主要介紹了Tensorflow與Keras自適應(yīng)使用顯存方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-06-06
  • 最新評(píng)論