最近2018中文字幕在日韩欧美国产成人片_国产日韩精品一区二区在线_在线观看成年美女黄网色视频_国产精品一区三区五区_国产精彩刺激乱对白_看黄色黄大色黄片免费_人人超碰自拍cao_国产高清av在线_亚洲精品电影av_日韩美女尤物视频网站

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
pythonMultipartEncoder如何傳輸zip文件-創(chuàng)新互聯(lián)

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

專注于為中小企業(yè)提供網(wǎng)站制作、網(wǎng)站設(shè)計(jì)服務(wù),電腦端+手機(jī)端+微信端的三站合一,更高效的管理,為中小企業(yè)邢臺(tái)免費(fèi)做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動(dòng)了上千家企業(yè)的穩(wěn)健成長,幫助中小企業(yè)通過網(wǎng)站建設(shè)實(shí)現(xiàn)規(guī)模擴(kuò)充和轉(zhuǎn)變。python可以做什么

Python是一種編程語言,內(nèi)置了許多有效的工具,Python幾乎無所不能,該語言通俗易懂、容易入門、功能強(qiáng)大,在許多領(lǐng)域中都有廣泛的應(yīng)用,例如最熱門的大數(shù)據(jù)分析,人工智能,Web開發(fā)等。

需求:對(duì)方提供處理文件的接口,本地將待處理文件壓縮后,通過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ì)方接口說明設(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)求由原始方法演變而來的。

multipart/form-data的基礎(chǔ)方法是post,也就是說是由post方法來組合實(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)容自然需要分割開來,不然接收方就無法正常解析和還原這個(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文件”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!


名稱欄目:pythonMultipartEncoder如何傳輸zip文件-創(chuàng)新互聯(lián)
網(wǎng)站URL:http://fisionsoft.com.cn/article/eoggc.html