如何优雅的封装requests

搭建接口自动化测试框架,一般都要对post/get请求做封装。

一般的封装过程是,

class MyRequest:
    def my_post():
        """do something"""
        requests.post(url=url,json=data,headers=self.headers)
    def my_get():
        """do something"""
        requests.get(url=url,params=params,headers=self.headers)

然而,借助装饰器,可以实现更优雅的封装。

在这之前,先打开requests.api.request,看看源码。

# -*- coding: utf-8 -*-

"""
requests.api
~~~~~~~~~~~~

This module implements the Requests API.

:copyright: (c) 2012 by Kenneth Reitz.
:license: Apache2,see LICENSE for more details.
"""

from . import sessions


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','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)


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',**kwargs)


def options(url,**kwargs):
    r"""Sends an OPTIONS request.

    :param url: URL for the new :class:`Request` object.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
    """

    kwargs.setdefault('allow_redirects',True)
    return request('options',**kwargs)


def head(url,**kwargs):
    r"""Sends a HEAD request.

    :param url: URL for the new :class:`Request` object.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
    """

    kwargs.setdefault('allow_redirects',False)
    return request('head',**kwargs)


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,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',data=data,json=json,**kwargs)


def put(url,**kwargs):
    r"""Sends a PUT request.

    :param url: URL for the new :class:`Request` object.
    :param data: (optional) Dictionary,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('put',**kwargs)


def patch(url,**kwargs):
    r"""Sends a PATCH request.

    :param url: URL for the new :class:`Request` object.
    :param data: (optional) Dictionary,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('patch',**kwargs)


def delete(url,**kwargs):
    r"""Sends a DELETE request.

    :param url: URL for the new :class:`Request` object.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
    """

    return request('delete',**kwargs)

首先定义了1个request函数。

后面定义了get/options/head/post/put/patch/delete 6个函数。

后面的6个函数,内部都在调用第一个request函数。只是传参不同。

显而易见,源码已经按不同的method做了一次封装了。

我们自己的封装就不要再定义my_get/my_post了,直接在这层封装上,加入我们自己的额外代码就好了。

装饰器,就能把我们自己的额外代码,优雅的加上去。

装饰器,长这样,

def decorator(post):
    def wrap():
        post()
    return wrap

如果加到post函数上去,

@decorator
def post()

就等价于,

post = decorator(post)

看到没有,我们可以在decorator里面搞事情了!

在搞事情前,先建个MyRequest,把requests.api.request的代码原封不动的沾过来,加上我们的装饰器@method

from requests.api import request

class MyRequest:
    
    #  def request可以不用添加
    
    @method
    def get(self,**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',**kwargs)

    @method
    def options(self,**kwargs):
        r"""Sends an OPTIONS request.

        :param url: URL for the new :class:`Request` object.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :return: :class:`Response <Response>` object
        :rtype: requests.Response
        """

        kwargs.setdefault('allow_redirects',True)
        return request('options',**kwargs)

    @method
    def head(self,**kwargs):
        r"""Sends a HEAD request.

        :param url: URL for the new :class:`Request` object.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :return: :class:`Response <Response>` object
        :rtype: requests.Response
        """

        kwargs.setdefault('allow_redirects',False)
        return request('head',**kwargs)

    @method
    def post(self,**kwargs):
        r"""Sends a POST request.

        :param url: URL for the new :class:`Request` object.
        :param data: (optional) Dictionary,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',**kwargs)

    @method
    def put(self,**kwargs):
        r"""Sends a PUT request.

        :param url: URL for the new :class:`Request` object.
        :param data: (optional) Dictionary,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('put',**kwargs)

    @method
    def patch(self,**kwargs):
        r"""Sends a PATCH request.

        :param url: URL for the new :class:`Request` object.
        :param data: (optional) Dictionary,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('patch',**kwargs)

    @method
    def delete(self,**kwargs):
        r"""Sends a DELETE request.

        :param url: URL for the new :class:`Request` object.
        :return: :class:`Response <Response>` object
        :rtype: requests.Response
        """

        return request('delete',**kwargs)

接着再来实现method装饰器,这里有点不同的是,装饰器作用在类的方法上面的,参数有些区别,

def method(f):
    # do something
    def send(self,*args,**kwargs):
        # do something
        return f(self,**kwargs)
    # do something
    return send

send的第一个参数为self,跟类方法对应。

第二、第三个参数兼容了get/post等不同的传参,

return f(self,**kwargs)
#  等价于
return get(self,**kwargs)
# 或
return post(self,**kwargs)

优雅!

至于装饰器里面的do something,可以是记录耗时,打印日志,重试机制,等。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


背景:计算机内部用补码表示二进制数。符号位1表示负数,0表示正数。正数:无区别,正数 的原码= 反码 = 补码重点讨论负数若已知 负数 -8,则其原码为:1000 1000,(1为符号位,为1代表负数,为0代表正数)反码为:1111 0111,(符号位保持不变,其他位置按位取反)补码为:1111 1000,(反码 + 1)即在计算机中 用 1111 1000表示 -8若已知补码为 1111 1000,如何求其原码呢?(1)方法1:求负数 原码---&gt;补...
大家好,我们现在来讲解关于加密方面的知识,说到加密我认为不得不提MD5,因为这是一种特殊的加密方式,它到底特殊在哪,现在我们就开始学习它全称:message-digest algorithm 5翻译过来就是:信息 摘要 算法 5加密和摘要,是不一样的加密后的消息是完整的;具有解密算法,得到原始数据;摘要得到的消息是不完整的;通过摘要的数据,不能得到原始数据;所以,当看到很多人说,md5,加密,解密的时候,呵呵一笑就好了。MD5长度有人说md5,128位,32位,16位,到
相信大家在大学的《算法与数据结构》里面都学过快速排序(QuickSort), 知道这种排序的性能很好,JDK里面直到JDK6用的都是这种经典快排的算法。但是到了JDK7的时候JDK内置的排序算法已经由经典快排变成了Dual-Pivot排序算法。那么Dual-Pivot到底是何方圣神,能比我们学过的经典快排还要快呢?我们一起来看看。经典快排在学习新的快排之前,我们首先来复习一下经典快排,它的核心思想是:接受一个数组,挑一个数(pivot),然后把比它小的那一摊数放在它的左边,把比它大的那一摊数放
加密在编程中的应用的是非常广泛的,尤其是在各种网络协议之中,对称/非对称加密则是经常被提及的两种加密方式。对称加密我们平时碰到的绝大多数加密就是对称加密,比如:指纹解锁,PIN 码锁,保险箱密码锁,账号密码等都是使用了对称加密。对称加密:加密和解密用的是同一个密码或者同一套逻辑的加密方式。这个密码也叫对称秘钥,其实这个对称和不对称指的就是加密和解密用的秘钥是不是同一个。我在上大学的时候做过一个命令行版的图书馆管理系统作为 C 语言课设。登入系统时需要输入账号密码,当然,校验用户输入的密码
前言我的目标是写一个非常详细的关于diff的干货,所以本文有点长。也会用到大量的图片以及代码举例,目的让看这篇文章的朋友一定弄明白diff的边边角角。先来了解几个点...1. 当数据发生变化时,vue是怎么更新节点的?要知道渲染真实DOM的开销是很大的,比如有时候我们修改了某个数据,如果直接渲染到真实dom上会引起整个dom树的重绘和重排,有没有可能我们只更新我们修改的那一小块dom而不要更新整个dom呢?diff算法能够帮助我们。我们先根据真实DOM生成一颗virtual DOM,当v
对称加密算法 所有的对称加密都有一个共同的特点:加密和解密所用的密钥是相同的。现代对称密码可以分为序列密码和分组密码两类:序列密码将明文中的每个字符单独加密后再组合成密文;而分组密码将原文分为若干个组,每个组进行整体加密,其最终加密结果依赖于同组的各位字符的具体内容。也就是说,分组加密的结果不仅受密钥影响,也会受到同组其他字符的影响。序列密码分组密码序列密码的安全性看上去要更弱一些,但是由于序列密码只需要对单个位进行操作,因此运行速度比分组加密要快...
本文介绍RSA加解密中必须考虑到的密钥长度、明文长度和密文长度问题,对第一次接触RSA的开发人员来讲,RSA算是比较复杂的算法,RSA算法自己其实也很简单,RSA的复杂度是由于数学家把效率和安全也考虑进去的缘故。html本文先只谈密钥长度、明文长度和密文长度的概念知识,RSA的理论及示例等之后再谈。提到密钥,咱们不得不提到RSA的三个重要大数:公钥指数e、私钥指数d和模值n。这三个大数是咱们使用RSA时须要直接接触的,理解了本文的基础概念,即便未接触过RSA的开发人员也能应对自如的使用RSA相关函数库,
直观的说,bloom算法类似一个hash set,用来判断某个元素(key)是否在某个集合中。和一般的hash set不同的是,这个算法无需存储key的值,对于每个key,只需要k个比特位,每个存储一个标志,用来判断key是否在集合中。算法:1. 首先需要k个hash函数,每个函数可以把key散列成为1个整数2. 初始化时,需要一个长度为n比特的数组,每个比特位初始化为03. 某个key加入集合时,用k个hash函数计算出k个散列值,并把数组中对应的比特位置为14. 判断某个key是否在集合时
你会用什么样的算法来为你的用户保存密码?如果你还在用明码的话,那么一旦你的网站被hack了,那么你所有的用户口令都会被泄露了,这意味着,你的系统或是网站就此完蛋了。所以,我们需要通过一些不可逆的算法来保存用户的密码。比如:MD5, SHA1, SHA256, SHA512, SHA-3,等Hash算法。这些算法都是不可逆的。系统在验证用户的口令时,需要把Hash加密过后的口令与后面存放口令的数据库中的口令做比较,如果一致才算验证通过。但你觉得这些算法好吗?我说的是:MD5, SHA1, SHA256,
在日常工作中经常会使用excel,有时在表格中需要筛选出重复的数据,该怎么操作呢?1、以下图中的表格数据为例,筛选出列中重复的内容;2、打开文件,选中需要筛选的数据列,依次点击菜单项【开始】-【条件格式】-【突出显示单元格规则】-【重复值】;3、将重复的值突出颜色显示;4、选中数据列,点击【数据】-【筛选】;5、点击列标题的的下拉小三角,点击【按颜色筛选】,即可看到重复的数据;...
工作中经常有和第三方机构联调接口的事情,顾将用到过的做以记录。 在和第三方联调时,主要步骤为:网络、加解密/签名验签、接口数据等,其中接口数据没啥好说的。 在联调前就需要先将两边的网络连通,一般公司的生产环境都加了防火墙,测试环境有的是有防火墙,有的则没有防火墙,这个需要和第三方人员沟通,如果有防火墙的就需要将我们的出口ip或域名发送给第三方做配置,配置了之后网络一般都是通的。加解密与签名验签: 一般第三方公司都会有加解密或签名验签的,毕竟为了数据安全。一般就是三...
此文章不包含认证机制。任何应用考虑到安全,绝不能明文的方式保存密码。密码应该通过某种方式进行加密。如今已有很多标准的算法比如SHA或者MD5再结合salt(盐)使用是一个不错的选择。废话不多说!直接开始SpringBoot 中提供了Spring Security:BCryptPasswordEncoder类,实现Spring的PasswordEncoder接口使用BCrypt强哈希方法来加密密码。第一步:pom导入依赖:&lt;dependency&gt; &lt;groupId...
前言在所有的加密算法中使用最多的就是哈希加密了,很多人第一次接触的加密算法如MD5、SHA1都是典型的哈希加密算法,而哈希加密除了用在密码加密上,它还有很多的用途,如提取内容摘要、生成签名、文件对比、区块链等等。这篇文章就是想详细的讲解一下哈希加密,并分享一个哈希加密的工具类。概述哈希函数(Hash Function),也称为散列函数或杂凑函数。哈希函数是一个公开函数,可以将任意长度的消息M映射成为一个长度较短且长度固定的值H(M),称H(M)为哈希值、散列值(Hash Value)、杂凑值或者消息
#快速排序解释 快速排序 Quick Sort 与归并排序一样,也是典型的分治法的应用。 (如果有对 归并排序还不了解的童鞋,可以看看这里哟~ 归并排序)❤❤❤ ###快速排序的分治模式 1、选取基准
#堆排序解释 ##什么是堆 堆 heap 是一种近似完全二叉树的数据结构,其满足一下两个性质 1. 堆中某个结点的值总是不大于(或不小于)其父结点的值; 2. 堆总是一棵完全二叉树 将根结点最大的堆叫
#前言 本文章是建立在插入排序的基础上写的喔,如果有对插入排序还有不懂的童鞋,可以看看这里。 ❤❤❤ 直接/折半插入排序 2路插入排序 ❤❤❤ #希尔排序解释 希尔排序 Shell Sort 又名&q
#归并排序解释 归并排序 Merge Sort 是典型的分治法的应用,其算法步骤完全遵循分治模式。 ##分治法思想 分治法 思想: 将原问题分解为几个规模较小但又保持原问题性质的子问题,递归求解这些子
#前言 本文章是建立在冒泡排序的基础上写的,如还有对 冒泡排序 不了解的童鞋,可以看看这里哦~ 冒泡排序 C++ #双向冒泡排序原理 双向冒泡排序 的基本思想与 冒泡排序还是一样的。冒泡排序 每次将相
#插入排序解释 插入排序很好理解,其步骤是 :先将第一个数据元素看作是一个有序序列,后面的 n-1 个数据元素看作是未排序序列。对后面未排序序列中的第一个数据元素在这个有序序列中进行从后往前扫描,找到
#桶排序解释 ##桶排序思想 桶排序 是一种空间换取时间的排序方式,是非基于比较的。 桶排序 顾名思义,就是构建多个映射数据的桶,将数据放入桶内,对每个桶内元素进行单独排序。假设我们有 n 个待排序的