python上传文件接口类型,以及异步接口类型

以下接口上传文件:
接口地址:/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)

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值