欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-25 11:05:12
目录在上一篇python接口自动化测试系列文章:python接口自动化浅析token应用原理,介绍token基本概念、运行原理及在自动化中接口如何携带token进行访问。以下主要介绍如何封装请求还记得...

在上一篇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请求封装的资料请关注其它相关文章!