Python通过Requests模块上传文件并请求接口
接口返回示例
{
"status": "0",
"msg": "成功",
"data": "操作成功"
}
定义调用该接口函数
import requests
import json
host = {"test":"https://test-xxx/upgrade-server", "online":"https://lc-xxx/upgrade-server"}
choose = host['test']
def fileUpload(file_path, file_name):
url = choose + "/file/upload"
files=[
('file',(file_name,open(file_path + file_name,'rb'),'application/octet-stream'))
]
version = "8.0.0"
data = {"version": version}
headers = {}
try:
re = requests.post(url=url, data=data, files=files, headers=headers)
print(re.text)
re_json = re.json()
fileSize = re_json['data']['fileSize']
filePath = re_json['data']['filePath']
fileMd5 = re_json['data']['fileMd5']
return fileSize, filePath, fileMd5
except Exception as e:
print(e)
pass
postman可以查看对应dorm-data形式上传参数的对应语言代码
在views中进行请求
def fileUpload(version, file):
url = choose + "/file/upload"
print(file)
files = [
('file', (file.name, file, 'application/octet-stream'))
]
data = {"version": version}
headers = {}
try:
print("version: ", version)
re = requests.post(url=url, data=data, files=files, headers=headers)
print(re)
re_json = re.json()
fileSize = re_json['data']['fileSize']
filePath = re_json['data']['filePath']
fileMd5 = re_json['data']['fileMd5']
arr = {}
arr['fileSize'] = fileSize
arr['filePath'] = filePath
arr['fileMd5'] = fileMd5
arr = json.dumps(arr)
return HttpResponse(arr, content_type='application/json')
except Exception as e:
print(e)
pass