介面測試 - python - 檔案匯入(上傳)/匯出
阿新 • • 發佈:2022-04-06
匯入(上傳):
批量導入藥店:
import requests # 請求url url = "https://a-test.yljk.cn/api/yft/user/agency_drug_store/import/" # 請求體 files = { 'attachment': open('/Users/zhangyang/Downloads/123.xlsx', 'rb') } data = { 'agencyDrugStoreImportParamJson': '{"parentId": "206715985112072192","imageReferParam": []}' }# 請求頭 headers = { 'terminal': 'WEBPC', 'token': 'SUPER_USER:VZZ99U0oLepnxZIWQqsLIOzZXw8NyQYF9bKspG5fxvI=f2239fb043f1400d9ae450570c6223fb' } response = requests.post(url, headers=headers, data=data, files=files) # response = requests.request("POST", url, headers=headers, data=data, files=files) #斷言 print(response.headers) assert response.headers['Succeed'] == 'succeed' # print(response.text)
上傳圖片:
def o_call(self, token): files = { "files": open(IMAGE_DIR + 'image1.png', 'rb') # 使用二進位制形式開啟 # "files": open('./image/image1.png', 'rb') # ./指當前工作路徑,而非當前檔案所在目錄} data = { "dirName": "AUTO_TEST" } # 上傳的圖片,在oss中,在AUTO_TEST目錄下 headers = { "token": token, "product": "WEBPC", # "Content-Type": "multipart/form-data" # 帶上這一句會報錯:Required request part 'files' is not present } return self.api_url.u_call(files=files, data=data, headers=headers)
匯出:
返回的response為資料流,需要儲存為檔案
import requests # 請求url url = 'https://a.b.com/api/aaa/bbb/ccc/super/export?_t=1649237095' # 請求頭 headers = { 'terminal': 'WEBPC', 'token': '123456' } response = requests.get(url=url, headers=headers) # 斷言 print(response.headers) assert 'attachment;filename=' in response.headers['Content-Disposition'] # 返回response是資料流,將檔案流儲存到檔案 with open('/Users/zhangyang/Downloads/doctor.xlsx', 'wb') as fd: for chunk in response.iter_content(): fd.write(chunk)
ps:
https://cn.python-requests.org/zh_CN/latest/user/quickstart.html#id5