Python接口自动化之request请求封装

这篇具有很好参考价值的文章主要介绍了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两个参数去掉。

最后感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:【文末领取】


     【下面是我整理的2023年最全的软件测试工程师学习知识架构体系图+全套资料】


一、Python编程入门到精通

二、接口自动化项目实战

Python接口自动化之request请求封装,软件测试,软件测试工程师,自动化测试,运维,python,软件测试,程序人生,自动化测试,职场发展,自动化

三、Web自动化项目实战

四、App自动化项目实战

Python接口自动化之request请求封装,软件测试,软件测试工程师,自动化测试,运维,python,软件测试,程序人生,自动化测试,职场发展,自动化

五、一线大厂简历

六、测试开发DevOps体系

Python接口自动化之request请求封装,软件测试,软件测试工程师,自动化测试,运维,python,软件测试,程序人生,自动化测试,职场发展,自动化

七、常用自动化测试工具

八、JMeter性能测试

Python接口自动化之request请求封装,软件测试,软件测试工程师,自动化测试,运维,python,软件测试,程序人生,自动化测试,职场发展,自动化

九、总结(尾部小惊喜)

生命不息,奋斗不止。每一份努力都不会被辜负,只要坚持不懈,终究会有回报。珍惜时间,追求梦想。不忘初心,砥砺前行。你的未来,由你掌握!

生命短暂,时间宝贵,我们无法预知未来会发生什么,但我们可以掌握当下。珍惜每一天,努力奋斗,让自己变得更加强大和优秀。坚定信念,执着追求,成功终将属于你!

只有不断地挑战自己,才能不断地超越自己。坚持追求梦想,勇敢前行,你就会发现奋斗的过程是如此美好而值得。相信自己,你一定可以做到!文章来源地址https://www.toymoban.com/news/detail-646624.html

到了这里,关于Python接口自动化之request请求封装的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • python接口自动化之request请求,如何使用 Python调用 API?

        尊重原创,转载请注明出处,谢谢!!

    2024年02月08日
    浏览(40)
  • 接口自动化【一】(抓取后台登录接口+postman请求通过+requests请求通过+json字典区别)

    文章目录 前言 一、requests库的使用 二、json和字典的区别 三、后端登录接口-请求数据生成 四、接口自动化-对应电商项目中的功能 五、来自postman的代码-后端登录 总结 记录:json和字典的区别,json和字段的相互转化;postman发送请求与Python中代码发送请求的区别。 安装: p

    2024年02月01日
    浏览(41)
  • Python 接口自动化 —— requests框架

    Python内置的urllib模块,也可以用于访问网络资源。但是,它用起来比较麻烦,而且,缺少很多实用的高级功能。因此我们使用 requests 模块进行进行接口测试。 requests官方文档资料地址: http://cn.python-requests.org/zh_CN/latest/ cmd(win+R快捷键)输入: 提示以下信息表示安装成功。

    2024年02月08日
    浏览(35)
  • Python+Requests实现接口自动化测试

    一般对于自动化的理解,有两种方式的自动化。 第一,不需要写代码,完全由工具实现,这种方式的工具一般是公司自己研发的,方便黑盒测试人员使用。这种工具的特点是学习成本低,方便使用,但是通用性不强,也就是换了一家公司,就很有可能无法使用之前的工具。

    2024年01月16日
    浏览(55)
  • python+requests接口自动化框架的实现

    为什么要做接口自动化框架 1、业务与配置的分离 2、数据与程序的分离;数据的变更不影响程序 3、有日志功能,实现无人值守 4、自动发送测试报告 5、不懂编程的测试人员也可以进行测试 正常接口测试的流程是什么? 确定接口测试使用的工具-----配置需要的接口参数----

    2024年03月13日
    浏览(39)
  • python接口自动化测试 requests库的基础使用

    目录 简单介绍 Get请求 Post请求 其他类型请求 自定义headers和cookies SSL 证书验证 响应内容 获取header 获取cookies requests库简单易用的HTTP库   格式:  requests.get(url)  注意: 若需要传请求参数,可直接在 url 最后的 ? 后面,也可以调用 get() 时多加一个参数 params ,传入请求

    2023年04月26日
    浏览(38)
  • 接口自动化测试:Python+Pytest+Requests+Allure

    本项目实现了对Daily Cost的接口测试: Python+Requests 发送和处理HTTP协议的请求接口 Pytest 作为测试执行器 YAML 管理测试数据 Allure 来生成测试报告。 本项目是参考了pytestDemo做了自己的实现。 项目结构 api : 接口封装层,如封装HTTP接口为Python接口 commom : 从文件中读取数据等各种

    2024年02月09日
    浏览(43)
  • python3+requests+unittest接口自动化测试

    python3 + pycharm编辑器 (该套代码只是简单入门,有兴趣的可以不断后期完善) (1)run.py主运行文件,运行之后可以生成相应的测试报告,并以邮件形式发送; (2)report文件夹存放测试结果报告; (3)unit_test文件夹是存放测试用例(demo.py和test_unittest.py用例用法介绍,实际

    2024年02月09日
    浏览(40)
  • 【实战详解】如何快速搭建接口自动化测试框架?Python + Requests

    本文主要介绍如何使用Python语言和Requests库进行接口自动化测试,并提供详细的代码示例和操作步骤。希望能对读者有所启发和帮助。 随着移动互联网的快速发展,越来越多的应用程序采用Web API(也称为RESTful API)作为数据交换的主要方式。针对API进行自动化测试已经变得非

    2024年02月09日
    浏览(39)
  • Python+Requests+Pytest+YAML+Allure实现接口自动化

    本项目实现接口自动化的技术选型:Python+Requests+Pytest+YAML+Allure ,主要是针对之前开发的一个接口项目来进行学习,通过 Python+Requests 来发送和处理HTTP协议的请求接口,使用 Pytest 作为测试执行器,使用 YAML 来管理测试数据,使用 Allure 来生成测试报告 本项目在实现过程中,把

    2024年02月11日
    浏览(38)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包