Python接口自动化之request请求封装源码分析
作者:??行者AI???? 发布时间:2023-12-29 02:42:32
标签:Python,接口,自动化,request,请求,封装
前言:
我们在做自动化测试的时候,大家都是希望自己写的代码越简洁越好,代码重复量越少越好。那么,我们可以考虑将request的请求类型(如:Get、Post、Delect请求)都封装起来。这样,我们在编写用例的时候就可以直接进行请求了。
1. 源码分析
我们先来看一下Get、Post、Delect等请求的源码,看一下它们都有什么特点。
(1)Get请求源码
def get(self, url, **kwargs):
r"""Sends a GET request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', True)
return self.request('GET', url, **kwargs)
(2)Post请求源码
def post(self, url, data=None, json=None, **kwargs):
r"""Sends a POST request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
return self.request('POST', url, data=data, json=json, **kwargs)
(3)Delect请求源码
def delete(self, url, **kwargs):
r"""Sends a DELETE request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
return self.request('DELETE', url, **kwargs)
(4)分析结果
我们发现,不管是Get请求、还是Post请求或者是Delect请求,它们到最后返回的都是request函数。那么,我们再去看一看request函数的源码。
def request(self, method, url,
params=None, data=None, headers=None, cookies=None, files=None,
auth=None, timeout=None, allow_redirects=True, proxies=None,
hooks=None, stream=None, verify=None, cert=None, json=None):
"""Constructs a :class:`Request <Request>`, prepares it and sends it.
Returns :class:`Response <Response>` object.
:param method: method for the new :class:`Request` object.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query
string for the :class:`Request`.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json to send in the body of the
:class:`Request`.
:param headers: (optional) Dictionary of HTTP Headers to send with the
:class:`Request`.
:param cookies: (optional) Dict or CookieJar object to send with the
:class:`Request`.
:param files: (optional) Dictionary of ``'filename': file-like-objects``
for multipart encoding upload.
:param auth: (optional) Auth tuple or callable to enable
Basic/Digest/Custom HTTP Auth.
:param timeout: (optional) How long to wait for the server to send
data before giving up, as a float, or a :ref:`(connect timeout,
read timeout) <timeouts>` tuple.
:type timeout: float or tuple
:param allow_redirects: (optional) Set to True by default.
:type allow_redirects: bool
:param proxies: (optional) Dictionary mapping protocol or protocol and
hostname to the URL of the proxy.
:param stream: (optional) whether to immediately download the response
content. Defaults to ``False``.
:param verify: (optional) Either a boolean, in which case it controls whether we verify
the server's TLS certificate, or a string, in which case it must be a path
to a CA bundle to use. Defaults to ``True``.
:param cert: (optional) if String, path to ssl client cert file (.pem).
If Tuple, ('cert', 'key') pair.
:rtype: requests.Response
"""
# Create the Request.
req = Request(
method=method.upper(),
url=url,
headers=headers,
files=files,
data=data or {},
json=json,
params=params or {},
auth=auth,
cookies=cookies,
hooks=hooks,
)
prep = self.prepare_request(req)
proxies = proxies or {}
settings = self.merge_environment_settings(
prep.url, proxies, stream, verify, cert
)
# Send the request.
send_kwargs = {
'timeout': timeout,
'allow_redirects': allow_redirects,
}
send_kwargs.update(settings)
resp = self.send(prep, **send_kwargs)
return resp
从request源码可以看出,它先创建一个Request,然后将传过来的所有参数放在里面,再接着调用self.send(),并将Request传过去。这里我们将不在分析后面的send等方法的源码了,有兴趣的同学可以自行了解。
分析完源码之后发现,我们可以不需要单独在一个类中去定义Get、Post等其他方法,然后在单独调用request。其实,我们直接调用request即可。
2. requests请求封装
代码示例:
import requests
class RequestMain:
def __init__(self):
"""
session管理器
requests.session(): 维持会话,跨请求的时候保存参数
"""
# 实例化session
self.session = requests.session()
def request_main(self, method, url, params=None, data=None, json=None, headers=None, **kwargs):
"""
:param method: 请求方式
:param url: 请求地址
:param params: 字典或bytes,作为参数增加到url中
:param data: data类型传参,字典、字节序列或文件对象,作为Request的内容
:param json: json传参,作为Request的内容
:param headers: 请求头,字典
:param kwargs: 若还有其他的参数,使用可变参数字典形式进行传递
:return:
"""
# 对异常进行捕获
try:
"""
封装request请求,将请求方法、请求地址,请求参数、请求头等信息入参。
注 :verify: True/False,默认为True,认证SSL证书开关;cert: 本地SSL证书。如果不需要ssl认证,可将这两个入参去掉
"""
re_data = self.session.request(method, url, params=params, data=data, json=json, headers=headers, cert=(client_crt, client_key), verify=False, **kwargs)
# 异常处理 报错显示具体信息
except Exception as e:
# 打印异常
print("请求失败:{0}".format(e))
# 返回响应结果
return re_data
if __name__ == '__main__':
# 请求地址
url = '请求地址'
# 请求参数
payload = {"请求参数"}
# 请求头
header = {"headers"}
# 实例化 RequestMain()
re = RequestMain()
# 调用request_main,并将参数传过去
request_data = re.request_main("请求方式", url, json=payload, headers=header)
# 打印响应结果
print(request_data.text)
注 :如果你调的接口不需要SSL认证,可将cert与verify两个参数去掉。
3. 总结
本文简单的介绍了Python接口自动化之request请求封装
来源:https://juejin.cn/post/6972379762471731230


猜你喜欢
- MySQL使用环境变量TMPDIR的值作为保存临时文件的目录的路径名。如果未设置TMPDIR,MySQL将使用系统的默认值,通常为/tmp、
- 我们知道,临时表有以下特性: 1. SESSION 级别,SESSION 一旦断掉,就被自动DROP 了。 2. 和默认引擎有关。如果默认引
- “站内信”不同于电子邮件,电子邮件通过专门的邮件服务器发送、保存。而“站内信”是系统内的消息,说白了,“站内信”的实现,就是通过数据库插入记
- 本文实例讲述了Python实现检测文件MD5值的方法。分享给大家供大家参考,具体如下:前面介绍过Python计算文件md5值的方法,这里分析
- 使用pip安装python库的几种方式1、使用pip在线安装1.1 安装单个package格式如下:pip install SomePack
- 以前写过一个刷校内网的人气的工具,Java的(以后再也不行Java程序了),里面用到了验证码识别,那段代码不是我自己写的:-) 校内的验证是
- 题记:毕业一年多天天coding,好久没写paper了。在这动荡的日子里,也希望写点东西让自己静一静。恰好前段时间用python做了一点时间
- 1、概述 经常用到轮廓查找和多边形拟合等opencv操作,因此记录以备后续使用。本文代码中的阈值条件对图片没有实际意义,仅仅是为了测试。原图
- CSSer与其他IT职位一样,在找工作的时候,都会面临着面试官提出的问题,或者给出的试卷。一、超链接点击过后hover样式就不出现的问题?被
- 在实际的项目中,我们一般都会建立三个环境:开发、测试和生产环境,这三种环境会使用不同的配置组合,为了能方便地切换配置,我们可以为不同的环境创
- 【名称】Abs【类别】数学函数【原形】Abs(number)【参数】必选的。Number参数是一个任何有效的数值型表达式【返回值】同numb
- 简介HTTP协议规定post提交的数据必须放在消息主体中,但是协议并没有规定必须使用什么编码方式。服务端通过是根据请求头中的Content-
- 如果没有读过上面内容的读者,有兴趣的可以一阅。在上面的使用JdbcTemplate一文中,主要通过spring提供的JdbcTemplate
- 对着谷歌大神膜拜了一下午, 终于让我找到了一款免费的,国产货!!外观虽然不能跟老外的比,但是功能还挺全,实用就好。下载地址:http://x
- mysql使用left join连接出现重复问题描述在使用连接查询的时候,例如以A表为主表,左连接B表,我们期望的是A表有多少条记录,查询结
- Python编写一个简易银行账户系统,供大家参考,具体内容如下文章中主要涉及的方法是Python中的open(filename, ‘r
- PyQt5安装之前安装过anaconda,里面是含有pyqt的,在环境里搜索可以看到,但是针对实际开发,并没有全部的qt5工具,所以需要再次
- 这篇文章主要讲一下如何串行执行一组异步任务,例如有下面几个任务,在这里我们用setTimeout模拟一个异步任务:let taskA = (
- 前言大家都看过彩带飘落吧?这个在比较喜庆的场合是很常见的:还有“跑马灯”效果,听起来很陌生,其实很常见,下面的就是:来源:https://w
- 前言Javascript 团体的每个人都喜欢新的API,语法更新以及特性,它们提供了更好的,更智能,更有效的方式以完成重要的任务。继上一篇的