使用python 的request库写接口测试代码时,经常会遇到上传文件的场景。本文就是上传例子。
比如,后端提供了文件上传接口,使用python调用接口上传图片等附件,直接上代码
from urllib3 import encode_multipart_formdata
import requests
host = "http://*.*.*.*:80/"
def upload():
url = "upload/public"
params = {
}
header = {
"content-type":"application/json"
}
data = {
}
try:
filename="pic.jpeg"
file_path = "/Users/admin/Downloads/pic.jpeg"
data['file']= (filename, open(file_path,'rb').read())
encode_data = encode_multipart_formdata(data)
data = encode_data[0]
header['Content-Type'] = encode_data[1]
r = requests.post(url=host + url, headers=header, data=data)
print(r)
print("返回值:" + r.text)
except Exception as e:
print(e)
if __name__ == "__main__":
upload()
网友评论