以下接口上传文件:
接口地址:/api/v1/upfile/
请求方式:POST
- 一、如何使用python实现接口上传数据呢?
方法1:file单独拿出来,并作为参数传入
import os
import requests
file_path='D:\code\pytest_test\\file\\test.png'
relpath=os.path.relpath(file_path)
print(relpath)
host='http://****'
url=host+'/api/v1/upfile/'
files={
'file':('test.png',open(relpath,'rb'),'image/png') # rb以二进制方式读取
}
body={
'title':'测试一下'
}
r=requests.post(url=url,data=body,files=files)
print(r.text)
方法2:
使用requests-toolbelt插件的MultipartEncoder类
安装 pip install requests-toolbelt --index-url https://pypi.douban.com/simple
格式:
monitor = MultipartEncoderMonitor.from_fields(
fields={‘field0’: ‘value0’}, callback
)
headers = {‘Content-Type’: montior.content_type}
r = requests.post(‘https://httpbin.org/post’, data=monitor,
headers=headers)
from requests_toolbelt import MultipartEncoder
m=MultipartEncoder(
fields={
'file':('test.png',open(relpath,'rb'),'image/png'),
'title':'测试123'
}
)
r=requests.post(url=url,data=m,headers={'Content-Type': m.content_type})
print(r.text)
- 二、异步请求接口
异步请求接口,一般会在header显示为"X-Requested-With": “XMLHttpRequest”
我们根向以往一样传参即可。在header注明header的形式
url='http://*****/zentao/user-login.html'
body= {
"account": "lujingjing",
"password": "****",
"verifyRand": "585630153",
"keepLogin": "0",
"passwordStrength": "1",
"referer": "/zentao/"
}
h={'X-Requested-With':'XMLHttpRequest'}
res_yibu=requests.post(url,data=body,headers=h)
print(res_yibu.text)