python接口测试中不同的请求方式

创建一个session

s=requests.session

1、get请求方式

(1)get请求的时候对应的请求参数形式为Query String Parameters,参数直接反映在url里面,形式为key1=value1&key2=value2

例如:https://*****/taker_order_count?team_id=100&team_address=dsdsd

使用python发送请求时,直接使用params关键字,以一个字典来传递这些参数,如

params={"key1":"value1","key2":"value2"}

re = s.request(get,url=url,params=params)

2、post请求方式

(1) post请求content-type类型是:Content-Type:application/x-www-form-urlencoded,对应的请求参数形式为Form Data

使用requests发送请求时,只要将请求的参数构造成一个字典,然后使用data参数即可

data={"key1":"value1","key2":"value2"}

re = s.request(post,url=url,data=data)

注意:如果data中嵌套字典,一定要将字典转化成字符串,如:

info = { "appid": "123", "checkin_type": "6", "role": "1", "stunum": "15812086122" }

data = { 'Data': '%s' % info, 'MsgType': 'APP_SEND_CARDCHECKIN_BYSTUNUM' }

re = s.request(post,url=url,data=data)

(2)post请求content-type类型是:Content-Type:application/json对应的请求参数形式为request payload

Reqeusts支持以request payload形式发送post请求,application/json格式的请求头是指用来告诉服务端post过去的消息主体是序列化后的 JSON 字符串。使用python写接口自动化定义接口时需要使用json.dumps()将dict类型的数据转成str,因为如果直接将dict类型的数据写入json文件中会发生报错

params= {
'dealRemark': dealRemark,
'headApplyId': headApplyId,
'reassignedTakerId': reassignedTakerId,
'status': status,
'teamId': teamId,
'trackingId': trackingId
}
body = json.dumps(params)

re = s.request(post,url=url,data=data)

或者直接使用json关键字传递参数

re = s.request(post,url=url,json=params)

(3)传参带文件,post上传文件,首先需要构造file,格式如下,fp为文件路径,然后将构造好的file传给files即可

file = { 'file_name': open(fp, 'rb') }

re = s.request(post,url=url,jfiles=file)

(4)post请求 Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryrGKCBY7qhFd3TrwA

body = MultipartEncoder(fields=body_data,boundary='------' + ''.join(random.sample(string.ascii_letters + string.digits, 32)))
header['content-type'] = body.content_type

参考:

https://www.bbsmax.com/A/obzbN72MzE/

https://blog.csdn.net/m0_37556444/article/details/82845694

或者直接使用files关键字上传

#请求的接口url
url = "url"
 
#假设待上传文件与脚本在同一目录下
dir_path = os.path.abspath(os.path.dirname(__file__))
#待上传文件的路径,这里假设文件名为test.txt
file_path = os.path.join(dir_path,'test.txt')
 
'''
    field_1,field_2...field_n代表普通字段名
    value_1,value_2...value_n代表普通字段值
    files为文件类型字段
 
    实际应用中字段名field_n均需要替换为接口抓包得到的实际字段名
    对应的字段值value_n也需要替换为接口抓包得到的实际字段值
'''
files={
    'field_1':(None,'value_1'),
    'field_2':(None,'value_2'),
    ...
    'field_n':(None,'value_n'),
    'files':('test.txt',open(file_path,'rb'),'text/plain'),
}
 
r = s.post(url,files=files)

参考https://www.bbsmax.com/A/kvJ3jLBgzg/

本博客纯粹是学习过程中的笔记,部分来自转载或摘抄,如有侵权,请联系删除 email:18017870857@163.com
原文地址:https://www.cnblogs.com/yanzhuping/p/14108148.html