国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

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)分析結果

我們發(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ù)放在里面,再接著調用self.send(),并將Request傳過去。這里我們將不在分析后面的send等方法的源碼了,有興趣的同學可以自行了解。

分析完源碼之后發(fā)現(xiàn),我們可以不需要單獨在一個類中去定義Get、Post等其他方法,然后在單獨調用request。其實,我們直接調用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的內容
         :param json: json傳參,作為Request的內容
         :param headers: 請求頭,字典
         :param kwargs: 若還有其他的參數(shù),使用可變參數(shù)字典形式進行傳遞
         :return:
         """
 
         # 對異常進行捕獲
         try:
             """
             
             封裝request請求,將請求方法、請求地址,請求參數(shù)、請求頭等信息入?yún)ⅰ?             注 :verify: True/False,默認為True,認證SSL證書開關;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))
         # 返回響應結果
         return re_data


 if __name__ == '__main__':
     # 請求地址
     url = '請求地址'
     # 請求參數(shù)
     payload = {"請求參數(shù)"}
     # 請求頭
     header = {"headers"}
     # 實例化 RequestMain()
     re = RequestMain()
     # 調用request_main,并將參數(shù)傳過去
     request_data = re.request_main("請求方式", url, json=payload, headers=header)
     # 打印響應結果
     print(request_data.text)  

注 :如果你調的接口不需要SSL認證,可將cert與verify兩個參數(shù)去掉。

最后感謝每一個認真閱讀我文章的人,禮尚往來總是要有的,雖然不是什么很值錢的東西,如果你用得到的話可以直接拿走:【文末領取】


???? 【下面是我整理的2023年最全的軟件測試工程師學習知識架構體系圖+全套資料】


一、Python編程入門到精通

二、接口自動化項目實戰(zhàn)

Python接口自動化之request請求封裝,軟件測試,軟件測試工程師,自動化測試,運維,python,軟件測試,程序人生,自動化測試,職場發(fā)展,自動化

三、Web自動化項目實戰(zhàn)

四、App自動化項目實戰(zhàn)

Python接口自動化之request請求封裝,軟件測試,軟件測試工程師,自動化測試,運維,python,軟件測試,程序人生,自動化測試,職場發(fā)展,自動化

五、一線大廠簡歷

六、測試開發(fā)DevOps體系

Python接口自動化之request請求封裝,軟件測試,軟件測試工程師,自動化測試,運維,python,軟件測試,程序人生,自動化測試,職場發(fā)展,自動化

七、常用自動化測試工具

八、JMeter性能測試

Python接口自動化之request請求封裝,軟件測試,軟件測試工程師,自動化測試,運維,python,軟件測試,程序人生,自動化測試,職場發(fā)展,自動化

九、總結(尾部小驚喜)

生命不息,奮斗不止。每一份努力都不會被辜負,只要堅持不懈,終究會有回報。珍惜時間,追求夢想。不忘初心,砥礪前行。你的未來,由你掌握!

生命短暫,時間寶貴,我們無法預知未來會發(fā)生什么,但我們可以掌握當下。珍惜每一天,努力奮斗,讓自己變得更加強大和優(yōu)秀。堅定信念,執(zhí)著追求,成功終將屬于你!

只有不斷地挑戰(zhàn)自己,才能不斷地超越自己。堅持追求夢想,勇敢前行,你就會發(fā)現(xiàn)奮斗的過程是如此美好而值得。相信自己,你一定可以做到!文章來源地址http://www.zghlxwxcb.cn/news/detail-646624.html

到了這里,關于Python接口自動化之request請求封裝的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉載,請注明出處: 如若內容造成侵權/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

  • python接口自動化之request請求,如何使用 Python調用 API?

    python接口自動化之request請求,如何使用 Python調用 API?

    ? ? 尊重原創(chuàng),轉載請注明出處,謝謝?。?/p>

    2024年02月08日
    瀏覽(37)
  • 接口自動化【一】(抓取后臺登錄接口+postman請求通過+requests請求通過+json字典區(qū)別)

    接口自動化【一】(抓取后臺登錄接口+postman請求通過+requests請求通過+json字典區(qū)別)

    文章目錄 前言 一、requests庫的使用 二、json和字典的區(qū)別 三、后端登錄接口-請求數(shù)據(jù)生成 四、接口自動化-對應電商項目中的功能 五、來自postman的代碼-后端登錄 總結 記錄:json和字典的區(qū)別,json和字段的相互轉化;postman發(fā)送請求與Python中代碼發(fā)送請求的區(qū)別。 安裝: p

    2024年02月01日
    瀏覽(19)
  • Python 接口自動化 —— requests框架

    Python內置的urllib模塊,也可以用于訪問網(wǎng)絡資源。但是,它用起來比較麻煩,而且,缺少很多實用的高級功能。因此我們使用 requests 模塊進行進行接口測試。 requests官方文檔資料地址: http://cn.python-requests.org/zh_CN/latest/ cmd(win+R快捷鍵)輸入: 提示以下信息表示安裝成功。

    2024年02月08日
    瀏覽(23)
  • Python+Requests實現(xiàn)接口自動化測試

    Python+Requests實現(xiàn)接口自動化測試

    一般對于自動化的理解,有兩種方式的自動化。 第一,不需要寫代碼,完全由工具實現(xiàn),這種方式的工具一般是公司自己研發(fā)的,方便黑盒測試人員使用。這種工具的特點是學習成本低,方便使用,但是通用性不強,也就是換了一家公司,就很有可能無法使用之前的工具。

    2024年01月16日
    瀏覽(22)
  • python+requests接口自動化框架的實現(xiàn)

    python+requests接口自動化框架的實現(xiàn)

    為什么要做接口自動化框架 1、業(yè)務與配置的分離 2、數(shù)據(jù)與程序的分離;數(shù)據(jù)的變更不影響程序 3、有日志功能,實現(xiàn)無人值守 4、自動發(fā)送測試報告 5、不懂編程的測試人員也可以進行測試 正常接口測試的流程是什么? 確定接口測試使用的工具-----配置需要的接口參數(shù)----

    2024年03月13日
    瀏覽(28)
  • python3+requests+unittest接口自動化測試

    python3+requests+unittest接口自動化測試

    python3 + pycharm編輯器 (該套代碼只是簡單入門,有興趣的可以不斷后期完善) (1)run.py主運行文件,運行之后可以生成相應的測試報告,并以郵件形式發(fā)送; (2)report文件夾存放測試結果報告; (3)unit_test文件夾是存放測試用例(demo.py和test_unittest.py用例用法介紹,實際

    2024年02月09日
    瀏覽(25)
  • 接口自動化測試:Python+Pytest+Requests+Allure

    接口自動化測試:Python+Pytest+Requests+Allure

    本項目實現(xiàn)了對Daily Cost的接口測試: Python+Requests 發(fā)送和處理HTTP協(xié)議的請求接口 Pytest 作為測試執(zhí)行器 YAML 管理測試數(shù)據(jù) Allure 來生成測試報告。 本項目是參考了pytestDemo做了自己的實現(xiàn)。 項目結構 api : 接口封裝層,如封裝HTTP接口為Python接口 commom : 從文件中讀取數(shù)據(jù)等各種

    2024年02月09日
    瀏覽(127)
  • python接口自動化測試 requests庫的基礎使用

    python接口自動化測試 requests庫的基礎使用

    目錄 簡單介紹 Get請求 Post請求 其他類型請求 自定義headers和cookies SSL 證書驗證 響應內容 獲取header 獲取cookies requests庫簡單易用的HTTP庫 ? 格式: ?requests.get(url)? 注意: 若需要傳請求參數(shù),可直接在?url?最后的???后面,也可以調用?get()?時多加一個參數(shù)?params?,傳入請求

    2023年04月26日
    瀏覽(21)
  • 【Python+requests+unittest+excel】實現(xiàn)接口自動化測試框架

    【Python+requests+unittest+excel】實現(xiàn)接口自動化測試框架

    一、框架結構: ?工程目錄 二、Case文件設計 三、基礎包 base 3.1 封裝get/post請求(runmethon.py) 3.2 封裝mock(mock.py) 四、數(shù)據(jù)操作包 operation_data 4.1 獲取excel單元格中的內容(get_data.py) ? 4.2?獲取excel中每個列(data_config.py) 4.3?解決數(shù)據(jù)依賴(dependent.py?) 五、工具類包 to

    2024年02月15日
    瀏覽(23)
  • 【實戰(zhàn)詳解】如何快速搭建接口自動化測試框架?Python + Requests

    【實戰(zhàn)詳解】如何快速搭建接口自動化測試框架?Python + Requests

    本文主要介紹如何使用Python語言和Requests庫進行接口自動化測試,并提供詳細的代碼示例和操作步驟。希望能對讀者有所啟發(fā)和幫助。 隨著移動互聯(lián)網(wǎng)的快速發(fā)展,越來越多的應用程序采用Web API(也稱為RESTful API)作為數(shù)據(jù)交換的主要方式。針對API進行自動化測試已經(jīng)變得非

    2024年02月09日
    瀏覽(24)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包