最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python接口自動化之request請求封裝源碼分析

 更新時間:2022年06月16日 15:00:39   作者:??行者AI????  
這篇文章主要介紹了Python接口自動化之request請求封裝源碼分析,文章圍繞主題的相關(guān)資料展開詳細的內(nèi)容介紹,具有一定的參考價值,感興趣的小伙伴可以參考一下

前言:

我們在做自動化測試的時候,大家都是希望自己寫的代碼越簡潔越好,代碼重復(fù)量越少越好。那么,我們可以考慮將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)分析結(jié)果

我們發(fā)現(xiàn),不管是Get請求、還是Post請求或者是Delect請求,它們到最后返回的都是request函數(shù)。那么,我們再去看一看request函數(shù)的源碼。

	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源碼可以看出,它先創(chuàng)建一個Request,然后將傳過來的所有參數(shù)放在里面,再接著調(diào)用self.send(),并將Request傳過去。這里我們將不在分析后面的send等方法的源碼了,有興趣的同學(xué)可以自行了解。

分析完源碼之后發(fā)現(xiàn),我們可以不需要單獨在一個類中去定義Get、Post等其他方法,然后在單獨調(diào)用request。其實,我們直接調(diào)用request即可。

2. requests請求封裝

代碼示例:

	import requests
	class RequestMain:
	    def __init__(self):
	        """
	        session管理器
	        requests.session(): 維持會話,跨請求的時候保存參數(shù)
	        """
	        # 實例化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,作為參數(shù)增加到url中         
			:param data: data類型傳參,字典、字節(jié)序列或文件對象,作為Request的內(nèi)容
	        :param json: json傳參,作為Request的內(nèi)容
	        :param headers: 請求頭,字典
	        :param kwargs: 若還有其他的參數(shù),使用可變參數(shù)字典形式進行傳遞
	        :return:
	        """
	
	        # 對異常進行捕獲
	        try:
	            """
	            
	            封裝request請求,將請求方法、請求地址,請求參數(shù)、請求頭等信息入?yún)ⅰ?
	            注 :verify: True/False,默認為True,認證SSL證書開關(guān);cert: 本地SSL證書。如果不需要ssl認證,可將這兩個入?yún)⑷サ?
	            """
	            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))
	        # 返回響應(yīng)結(jié)果
	        return re_data
	if __name__ == '__main__':
	    # 請求地址
	    url = '請求地址'
	    # 請求參數(shù)
	    payload = {"請求參數(shù)"}
	    # 請求頭
	    header = {"headers"}
	    # 實例化 RequestMain()
	    re = RequestMain()
	    # 調(diào)用request_main,并將參數(shù)傳過去
	    request_data = re.request_main("請求方式", url, json=payload, headers=header)
	    # 打印響應(yīng)結(jié)果
	    print(request_data.text)  

 :如果你調(diào)的接口不需要SSL認證,可將certverify兩個參數(shù)去掉。

3. 總結(jié)

本文簡單的介紹了Python接口自動化之request請求封裝

到此這篇關(guān)于Python接口自動化之request請求封裝源碼分析的文章就介紹到這了,更多相關(guān)Python request 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python模塊glob函數(shù)示例詳解教程

    Python模塊glob函數(shù)示例詳解教程

    這篇文章主要介紹了Python模塊glob函數(shù)的示例詳解教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2021-10-10
  • python實現(xiàn)word 2007文檔轉(zhuǎn)換為pdf文件

    python實現(xiàn)word 2007文檔轉(zhuǎn)換為pdf文件

    這篇文章主要為大家詳細介紹了python實現(xiàn)word 2007文檔轉(zhuǎn)換為pdf文件,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-03-03
  • python更新數(shù)據(jù)庫中某個字段的數(shù)據(jù)(方法詳解)

    python更新數(shù)據(jù)庫中某個字段的數(shù)據(jù)(方法詳解)

    這篇文章主要介紹了python更新數(shù)據(jù)庫中某個字段的數(shù)據(jù)方法,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-11-11
  • 全面了解python字符串和字典

    全面了解python字符串和字典

    下面小編就為大家?guī)硪黄媪私鈖ython字符串和字典。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-07-07
  • python識別圖片中指定顏色的圖案并保存為圖片

    python識別圖片中指定顏色的圖案并保存為圖片

    本文介紹了如何使用Python識別圖片中的指定顏色圖案,并將識別結(jié)果保存為圖片,通過示例代碼和效果展示,可以學(xué)習(xí)到實現(xiàn)這一功能的具體方法,感興趣的朋友跟隨小編一起看看吧
    2025-01-01
  • Python趣味實例,實現(xiàn)一個簡單的抽獎刮刮卡

    Python趣味實例,實現(xiàn)一個簡單的抽獎刮刮卡

    這篇文章主要介紹了Python如何實現(xiàn)一個簡單的抽獎刮刮卡,文中講解非常細致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-07-07
  • Pytorch常用的維度轉(zhuǎn)換方法

    Pytorch常用的維度轉(zhuǎn)換方法

    在PyTorch中,我們經(jīng)常需要處理多維數(shù)據(jù),如張量tensors,這篇文章主要介紹了一些Pytorch常用的維度轉(zhuǎn)換方法,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2025-03-03
  • flask 實現(xiàn)token機制的示例代碼

    flask 實現(xiàn)token機制的示例代碼

    這篇文章主要介紹了flask 實現(xiàn)token機制的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11
  • flask重啟后端口被占用的問題解決(非kill)

    flask重啟后端口被占用的問題解決(非kill)

    本文主要介紹了flask重啟后端口被占用的問題解決(非kill),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-04-04
  • anaconda的安裝和配置環(huán)境及導(dǎo)入pycharm的方法

    anaconda的安裝和配置環(huán)境及導(dǎo)入pycharm的方法

    這篇文章主要介紹了anaconda的安裝和配置環(huán)境及導(dǎo)入pycharm的方法,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-03-03

最新評論

化州市| 香河县| 长寿区| 迭部县| 库伦旗| 兴和县| 江阴市| 弋阳县| 龙南县| 华亭县| 定州市| 南召县| 若尔盖县| 阳城县| 新乡市| 林周县| 吴忠市| 黎城县| 浙江省| 漯河市| 江阴市| 武安市| 华蓥市| 广平县| 昌宁县| 偃师市| 南丰县| 青州市| 环江| 临漳县| 天峨县| 龙川县| 衢州市| 安达市| 芒康县| 景洪市| 华蓥市| 珲春市| 营口市| 中卫市| 漠河县|