1. 程式人生 > 實用技巧 >python介面自動化(十五) multipart/form-data上傳多個附件

python介面自動化(十五) multipart/form-data上傳多個附件

前言

上傳附件的時候,檔案的name引數名稱是一樣的,python裡面key是不可以重複的,又如何處理引數名稱相同的情況?

上傳附件

OPMS——員工相簿上傳圖片,提示成功,訪問響應中的url也可以訪問到該圖片,web頁面和資料庫卻沒有該條資料;無解ing

-------------------------------------------------------------------------------------------------------------------------------

禪道專案

1.下面以禪道提交bug的時候上傳附件為例

2.fiddler抓包檢視請求引數,檢視到檔案上傳的引數如下:

上傳一個附件

1.把引數分開,表單的資料用data提交,檔案附件用files提交。

傳多個附件

1.傳多個檔案的時候如下,這兩個引數的name都是一樣的,如果用字典去傳key值,很顯然 python的key值是不能重複的。

2.這時候需要換個格式,傳list資料

3.上傳之後,檢視禪道上的圖片;

參考程式碼:

# coding:utf-8
import requests
import re
import hashlib
pw="P@ssw0rd"
s=requests.Session()
headers={
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36"
}
vrand=0
while(True):
    rs1=s.get("http://localhost/zentaopms/www/user-login.html",headers=headers)
    rs1.encoding='utf-8'
    #print(rs1.text)
    rand=re.findall(r"'verifyRand' value='(.+?)'",rs1.text)
    #print(rand[0])
    if len(rand[0])==10:
        vrand=rand[0]
        break
print(vrand)
#方式一
hash=hashlib.md5()
hash.update(pw.encode('utf-8'))
f=hash.hexdigest()+vrand
#print(f)
#方式二
hash2=hashlib.md5(f.encode('utf-8'))
pwd=hash2.hexdigest()
print(pwd)
data={
"account":"fuhui",
"password":pwd,
"referer":"http://localhost/zentaopms/www/bug-browse-6.html",
"verifyRand":vrand
}
rs2=s.post("http://localhost/zentaopms/www/user-login.html",headers=headers,data=data)
rs2.encoding='utf-8'
#print(rs2.text)
rs3=s.get("http://localhost/zentaopms/www/bug-browse-6.html",headers=headers)
rs3.encoding='utf-8'
#print(rs3.text)
result=re.findall(r"\<a href=\'\/zentaopms\/www\/user-logout.html' \>(.+?)\<\/a\>",rs3.text)
print(result)
if result[0]=="退出":
    print("登入成功")

#-----------------上傳附件-------------------------

url2="http://localhost/zentaopms/www/bug-create-6-0-moduleID=0.html"
d2={"product":"6",
   "module":"0",
   "project":"5",
   "openedBuild[]":"trunk",
   "assignedTo":"huyongqin",
   "type":"codeerror",
   "title":"python學習上傳多圖",
   "severity":"3",
   "pri":"3",
   "steps":"<p>[步驟]</p><br/><p>[結果]</p><br/><p>[期望]</p><br/>",
   "oldTaskID":"0",
    "uid":"5f2a0514c39db",
   "case":"0",
   "caseVersion":"0",
   "result":"0",
   "testtask":"0",
    # "labels[]":"2.png"
}
# file={
#     "files[]":("2.png",open("2.png","rb"),"image/jpeg")
# }
file={
    ("files[]",("2.png",open("2.png","rb"),"image/jpeg")),
    ("labels[]","2.png"),
    ("files[]",("qq.png",open("E:\\qq.png","rb"),"image/jpeg")), #圖片與當前指令碼非同一目錄,需要寫路徑目錄
    ("labels[]","qq.png"),
}
result2=s.post(url2,data=d2,headers=headers,files=file,allow_redirects=False)
result2.encoding="utf-8"
print(result2.content)

 執行結果