Python接口自动化浅析requests请求封装原理

目录
  • 以下主要介绍如何封装请求
    • 将常用的get、post请求封装起来
    • get请求源码:
    • post请求源码:
    • 再来研究下request源码:
    • 直接调用request函数

在上一篇Python接口自动化测试系列文章:Python接口自动化浅析Token应用原理,介绍token基本概念、运行原理及在自动化中接口如何携带token进行访问。

以下主要介绍如何封装请求

还记得我们之前写的get请求、post请求么?

大家应该有体会,每个请求类型都写成单独的函数,代码复用性不强。

接下来将请求类型都封装起来,自动化用例都可以用这个封装的请求类进行请求

将常用的get、post请求封装起来

import requests
class RequestHandler:
    def get(self, url, **kwargs):
        """封装get方法"""
        # 获取请求参数
        params = kwargs.get("params")
        headers = kwargs.get("headers")
        try:
            result = requests.get(url, params=params, headers=headers)
            return result
        except Exception as e:
            print("get请求错误: %s" % e)
    def post(self, url, **kwargs):
        """封装post方法"""
        # 获取请求参数
        params = kwargs.get("params")
        data = kwargs.get("data")
        json = kwargs.get("json")
        try:
            result = requests.post(url, params=params, data=data, json=json)
            return result
        except Exception as e:
            print("post请求错误: %s" % e)
    def run_main(self, method, **kwargs):
        """
        判断请求类型
        :param method: 请求接口类型
        :param kwargs: 选填参数
        :return: 接口返回内容
        """
        if method == 'get':
            result = self.get(**kwargs)
            return result
        elif method == 'post':
            result = self.post(**kwargs)
            return result
        else:
            print('请求接口类型错误')
if __name__ == '__main__':
    # 以下是测试代码
    # get请求接口
    url = 'https://api.apiopen.top/getJoke?page=1&count=2&type=video'
    res = RequestHandler().get(url)
    # post请求接口
    url2 = 'http://127.0.0.1:8000/user/login/'
    payload = {
        "username": "vivi",
        "password": "123456"
    }
    res2 = RequestHandler().post(url2,json=payload)
    print(res.json())
    print(res2.json())

请求结果如下:

{'code': 200, 'message': '成功!', 'result': [{'sid': '31004305', 'text': '羊:师傅,理个发,稍微修一下就行', 'type': 'video', 'thumbnail': 'http://wimg.spriteapp.cn/picture/2020/0410/5e8fbf227c7f3_wpd.jpg', 'video': 'http://uvideo.spriteapp.cn/video/2020/0410/5e8fbf227c7f3_wpd.mp4', 'images': None, 'up': '95', 'down': '1', 'forward': '0', 'comment': '25', 'uid': '23189193', 'name': '青川小舟', 'header': 'http://wimg.spriteapp.cn/profile/large/2019/12/24/5e01934bb01b5_mini.jpg', 'top_comments_content': None, 'top_comments_voiceuri': None, 'top_comments_uid': None, 'top_comments_name': None, 'top_comments_header': None, 'passtime': '2020-04-12 01:43:02'}, {'sid': '30559863', 'text': '机器人女友,除了不能生孩子,其他的啥都会,价格239000元', 'type': 'video', 'thumbnail': 'http://wimg.spriteapp.cn/picture/2020/0306/5e61a41172a1b_wpd.jpg', 'video': 'http://uvideo.spriteapp.cn/video/2020/0306/5e61a41172a1b_wpd.mp4', 'images': None, 'up': '80', 'down': '6', 'forward': '3', 'comment': '20', 'uid': '23131273', 'name': '水到渠成', 'header': 'http://wimg.spriteapp.cn/profile/large/2019/07/04/5d1d90349cd1a_mini.jpg', 'top_comments_content': '为游戏做的秀', 'top_comments_voiceuri': '', 'top_comments_uid': '10250040', 'top_comments_name': '不得姐用户', 'top_comments_header': 'http://wimg.spriteapp.cn/profile', 'passtime': '2020-04-11 20:43:49'}]}
{'token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6InZpdmkiLCJleHAiOjE1ODY4NTc0MzcsImVtYWlsIjoidml2aUBxcS5jb20ifQ.k6y0dAfNU2o9Hd9LFfxEk1HKgczlQfUaKE-imPfTsm4', 'user_id': 1, 'username': 'vivi'}

这样就完美了吗,no,no,no。

以上代码痛点如下:

代码量大:只是封装了get、post请求,加上其他请求类型,代码量较大;

缺少会话管理:请求之间如何保持会话状态。

我们再来回顾下get、post等请求源码,看下是否有啥特点。

get请求源码:

def get(url, params=None, **kwargs):
    r"""Sends a GET request.
    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary, list of tuples or bytes to send
        in the query string for the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
    """
    kwargs.setdefault('allow_redirects', True)
    return request('get', url, params=params, **kwargs)

post请求源码:

def post(url, data=None, json=None, **kwargs):
    r"""Sends a POST request.
    :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 data to send in the body of the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
    """
    return request('post', url, data=data, json=json, **kwargs)
 

仔细研究下,发现get、post请求返回的都是request函数。

再来研究下request源码:

def request(method, url, **kwargs):
    """Constructs and sends a :class:`Request <Request>`.
    :param method: method for the new :class:`Request` object.
    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary, list of tuples or bytes to send
        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) A JSON serializable Python object 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 ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
        ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
        or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
        defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
        to add for the file.
    :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
    :param timeout: (optional) How many seconds 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) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.
    :type allow_redirects: bool
    :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
    :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 stream: (optional) if ``False``, the response content will be immediately downloaded.
    :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
    Usage::
      >>> import requests
      >>> req = requests.request('GET', 'https://httpbin.org/get')
      <Response [200]>
    """
    # By using the 'with' statement we are sure the session is closed, thus we
    # avoid leaving sockets open which can trigger a ResourceWarning in some
    # cases, and look like a memory leak in others.
    with sessions.Session() as session:
        return session.request(method=method, url=url, **kwargs)

源码看起来很长,其实只有三行,大部分是代码注释。

从源码中可以看出,不管是get还是post亦或其他请求类型,最终都是调用request函数。

既然这样,我们可以不像之前那样,在类内定义get方法、post方法,而是定义一个通用的方法

直接调用request函数

看起来有点绕,用代码实现就清晰了。

import requests
class RequestHandler:
    def __init__(self):
        """session管理器"""
        self.session = requests.session()
    def visit(self, method, url, params=None, data=None, json=None, headers=None, **kwargs):
        return self.session.request(method,url, params=params, data=data, json=json, headers=headers,**kwargs)
    def close_session(self):
        """关闭session"""
        self.session.close()
if __name__ == '__main__':
    # 以下是测试代码
    # post请求接口
    url = 'http://127.0.0.1:8000/user/login/'
    payload = {
        "username": "vivi",
        "password": "123456"
    }
    req = RequestHandler()
    login_res = req.visit("post", url, json=payload)
    print(login_res.text)

响应结果:

{
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6InZpdmkiLCJleHAiOjE1ODY4Njk3ODQsImVtYWlsIjoidml2aUBxcS5jb20ifQ.OD4HIv8G0HZ_RCk-GTVAZ9ADRjwqr3o0E32CC_2JMLg",
    "user_id": 1,
    "username": "vivi"
}

这次请求封装简洁实用,当然小伙伴们也可以根据自己的需求自行封装。

以上就是Python接口自动化浅析requests请求封装原理的详细内容,更多关于Python接口自动化requests请求封装的资料请关注我们其它相关文章!

(0)

相关推荐

  • python接口自动化(十六)--参数关联接口后传(详解)

    简介 大家对前边的自动化新建任务之后,接着对这个新建任务操作了解之后,希望带小伙伴进一步巩固胜利的果实,夯实基础.因此再在沙场实例演练一下博客园的相关接口.我们用自动化发随笔之后,要想接着对这篇随笔操作,不用说就需 要用参数关联了,发随笔之后会有一个随笔的 id,获取到这个 id,继续操作传这个随笔 id 就可以了(博客园的登录机制已经变了,不能用账号和密码登录了,这里用 cookie 登录) 大致流程步骤:web界面操作登录抓包查看cookie->代码模拟cookie登录->web界面操作新

  • python接口自动化(十七)--Json 数据处理---一次爬坑记(详解)

    简介 有些 post 的请求参数是 json 格式的,这个前面发送post 请求里面提到过,需要导入 json模块处理.现在企业公司一般常见的接口因为json数据容易处理,所以绝大多数返回数据也是 json 格式的,我们在做判断时候,往往只需要提取其中 几个关键的参数就行,这时候我们就需要 json 来解析返回的数据了.首先来说一下笔者为何要单独写这么一篇,原因是:python 里面 bool 值是 True 和 False,json 里面 bool 值是 true和 false,并且区分大小写

  • python接口自动化测试之接口数据依赖的实现方法

    在做自动化测试时,经常会对一整套业务流程进行一组接口上的测试,这时候接口之间经常会有数据依赖,那么具体要怎么实现这个依赖呢. 思路如下: 抽取之前接口的返回值存储到全局变量字典中. 初始化接口请求时,解析请求头部.请求参数等信息中的全局变量并进行替换. 发出请求. 核心代码实现: 抽取接口的返回值存储到全局变量字典中 # 抽取接口的返回值存储到全局变量字典中 if set_global_vars and isinstance(set_global_vars, list): for set_glo

  • Python接口自动化测试框架运行原理及流程

    本文总结分享介绍接口测试框架开发,环境使用python3+selenium3+unittest+ddt+requests测试框架及ddt数据驱动,采用Excel管理测试用例等集成测试数据功能,以及使用HTMLTestRunner来生成测试报告,目前有开源的poman.Jmeter等接口测试工具,为什么还要开发接口测试框架呢?因接口测试工具也有存在几点不足. 测试数据不可控制.比如接口返回数据不可控,就无法自动断言接口返回的数据,不能断定是接口程序引起,还是测试数据变化引起的错误,所以需要做一些初

  • Python接口自动化浅析requests请求封装原理

    目录 以下主要介绍如何封装请求 将常用的get.post请求封装起来 get请求源码: post请求源码: 再来研究下request源码: 直接调用request函数 在上一篇Python接口自动化测试系列文章:Python接口自动化浅析Token应用原理,介绍token基本概念.运行原理及在自动化中接口如何携带token进行访问. 以下主要介绍如何封装请求 还记得我们之前写的get请求.post请求么? 大家应该有体会,每个请求类型都写成单独的函数,代码复用性不强. 接下来将请求类型都封装起来

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

    目录 1. 源码分析 2. requests请求封装 3. 总结 前言: 我们在做自动化测试的时候,大家都是希望自己写的代码越简洁越好,代码重复量越少越好.那么,我们可以考虑将request的请求类型(如:Get.Post.Delect请求)都封装起来.这样,我们在编写用例的时候就可以直接进行请求了. 1. 源码分析 我们先来看一下Get.Post.Delect等请求的源码,看一下它们都有什么特点. (1)Get请求源码 def get(self, url, **kwargs): r""

  • Python接口自动化浅析unittest单元测试原理

    目录 一.单元测试三连问 1.什么是单元测试? 2.为什么要做单元测试? 3.怎么做单元测试? 二.unittest模块说明 1.unittest简介 2.unittest组成 1.TestCase(测试用例): 2.TestSuite(测试套件): 3.TestLoader(测试用例加载器): 4.TextTestRunner(执行测试用例): 5.Test Fixture(测试环境数据准备和清理): 3.unittest核心工作原理 三.unittest单元测试 1.实现思路 2.使用介绍

  • Python接口自动化浅析登录接口测试实战

    目录 1.什么是接口? 那么,接口测试和功能测试的区别在哪呢? 2.如何开展接口测试? 3.如何设计接口用例? 1.获取接口文档 Fiddler 2.分析接口文档的接口,提取测试点 3.接口测试用例设计思路 4.接口测试其他范围 接口业务测试 接口的性能测试 接口安全测试 在项目下新建一个文件夹common 编写登录接口用例,调用封装的请求类. 对于用例的一些总结: 4.接口测试用例实战 在上一篇Python接口自动化测试系列文章:Python接口自动化浅析unittest单元测试原理,主要介绍

  • Python接口自动化浅析logging日志原理及模块操作流程

    目录 一.日志介绍 01 为什么需要日志? 02 什么是日志? 03 日志的用途是什么? 04 日志的级别分为哪些? 05 日志功能的实现 二.Logging模块 01 logging模块介绍 02 logging模块优势 03 logging日志框架的组成 04 logging函数中的具体参数 05 简单的日志小例子 06 自定义logger日志 在上一篇Python接口自动化测试系列文章:Python接口自动化浅析pymysql数据库操作流程,主要介绍pymysql安装.操作流程.语法基础及

  • Python接口自动化浅析数据驱动原理

    在上一篇Python接口自动化测试系列文章:Python接口自动化浅析登录接口测试实战,主要介绍接口概念.接口用例设计及登录接口测试实战. 以下主要介绍使用openpyxl模块操作excel及结合ddt实现数据驱动. 在此之前,我们已经实现了用unittest框架编写测试用例,实现了请求接口的封装,这样虽然已经可以完成接口的自动化测试,但是其复用性并不高. 我们看到每个方法(测试用例)的代码几乎是一模一样的,试想一下,在我们的测试场景中, 一个登录接口有可能会有十几条到几十条测试用例,如果每组数

  • Python接口自动化浅析logging封装及实战操作

    在上一篇Python接口自动化测试系列文章:Python接口自动化浅析logging日志原理及模块操作流程,主要介绍日志相关概念及logging日志模块的操作流程. 而在此之前介绍过yaml封装,数据驱动.配置文件.日志文件等独立的功能,我们将这些串联起来,形成一个完整的接口测试流程. 以下主要介绍将logging常用配置放入yaml配置文件.logging日志封装及结合登录用例讲解日志如何在接口测试中运用. 一.yaml配置文件 将日志中的常用配置,比如日志器名称.日志器等级及格式化放在配置文

  • Python接口自动化浅析yaml配置文件原理及用法

    目录 一.yaml介绍及使用 01 yaml简介 02 yaml语法规则 03 yaml数据结构 对象 数组 纯量 二.yaml配置文件的使用 01 yaml配置文件准备 02 yaml配置文件格式校验 三.yaml配置文件读写 01 安装pyYaml 02 yaml模块源码解析 load: dump: 03 读写yaml配置文件 在上一篇Python接口自动化测试系列文章:Python接口自动化浅析数据驱动原理,主要介绍openpyxl操作excel,结合ddt实现数据驱动. 在自动化过程中,

  • python接口自动化使用requests库发送http请求

    目录 前言 一.requests库 二.HTTP 请求方法 三.发送GET请求 四.发送POST请求 五.获取响应数据 六.高级操作 6.1文件下载 6.2文件上传 6.3SSL证书验证 6.4保持会话 6.5requests封装 总结 前言 今天笔者想和大家来聊聊python接口自动化如何使用requests库发送http请求,废话呢笔者就不多说了,直接进入正题. 一.requests库 什么是Requests ?Requests 是⽤Python语⾔编写,基于urllib,采⽤Apache2

  • Python接口自动化浅析如何处理接口依赖

    在前面的Python接口自动化测试系列文章:Python接口自动化浅析logging封装及实战操作, 其中介绍了将logging常用配置放入yaml配置文件.logging日志封装及结合登录用例讲解日志如何在接口测试中运用. 以下主要介绍如何提取token.将token作为类属性全局调用及充值接口如何携带token进行请求. 一.场景说明 在面试接口自动化时,经常会问,其他接口调用的前提条件是当前用户必须是登录状态,如何处理接口依赖? 在此之前我们介绍过session管理器保存会话状态. 如果接

随机推荐