接口测试 - python - 文件导入(上传)/导出


导入(上传):

批量导入药店:

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