Python接口自动化之request请求封装源码分析

 更新时间:2022年06月16日 15:00:39   作者:​ 行者AI   ​  
这篇文章主要介绍了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认证,可将certverify两个参数去掉。

3. 总结

本文简单的介绍了Python接口自动化之request请求封装

到此这篇关于Python接口自动化之request请求封装源码分析的文章就介绍到这了,更多相关Python request 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 3行Python代码实现图像照片抠图和换底色的方法

    3行Python代码实现图像照片抠图和换底色的方法

    这篇文章主要介绍了3行Python代码实现图像照片抠图和换底色的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-10-10
  • 利用Python将多张图片合成视频的实现

    利用Python将多张图片合成视频的实现

    这篇文章主要介绍了利用Python将多张图片合成视频的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-11-11
  • python实现简单聊天功能

    python实现简单聊天功能

    这篇文章主要为大家详细介绍了python实现简单聊天功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-07-07
  • jupyter notebook 增加kernel教程

    jupyter notebook 增加kernel教程

    这篇文章主要介绍了jupyter notebook 增加kernel教程,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-04-04
  • python中Flask框架简单入门实例

    python中Flask框架简单入门实例

    这篇文章主要介绍了python中Flask框架简单入门实例,以一个hello程序简单分析了Flask框架的使用技巧,需要的朋友可以参考下
    2015-03-03
  • Python 多个图同时在不同窗口显示的实现方法

    Python 多个图同时在不同窗口显示的实现方法

    今天小编就为大家分享一篇Python 多个图同时在不同窗口显示的实现方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-07-07
  • python爬虫今日热榜数据到txt文件的源码

    python爬虫今日热榜数据到txt文件的源码

    这篇文章主要介绍了python爬虫今日热榜数据到txt文件的源码,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-02-02
  • Python 实现平台类游戏添加跳跃功能

    Python 实现平台类游戏添加跳跃功能

    这篇文章主要介绍了Python 实现平台类游戏添加跳跃功能,,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-03-03
  • python3实现读取chrome浏览器cookie

    python3实现读取chrome浏览器cookie

    这里给大家分享的是python3读取chrome浏览器的cookie(CryptUnprotectData解密)的代码,主要思路是读取到的cookies被封装成字典,可以直接给requests使用。
    2016-06-06
  • 利用Pytorch实现ResNet网络构建及模型训练

    利用Pytorch实现ResNet网络构建及模型训练

    这篇文章主要为大家介绍了利用Pytorch实现ResNet网络构建及模型训练详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-04-04

最新评论