python對(duì)于requests的封裝方法詳解-創(chuàng)新互聯(lián)

由于requests是http類接口的核心,因此封裝前考慮問題比較多:

創(chuàng)新互聯(lián)成立與2013年,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目成都做網(wǎng)站、成都網(wǎng)站制作、成都外貿(mào)網(wǎng)站建設(shè)網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元淳安做網(wǎng)站,已為上家服務(wù),為淳安各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:18982081108

1. 對(duì)多種接口類型的支持;

2. 連接異常時(shí)能夠重連;

3. 并發(fā)處理的選擇;

4. 使用方便,容易維護(hù);

當(dāng)前并未全部實(shí)現(xiàn),后期會(huì)不斷完善。重點(diǎn)提一下并發(fā)處理的選擇:python的并發(fā)處理機(jī)制由于存在GIL的原因,實(shí)現(xiàn)起來并不是很理想,綜合考慮多進(jìn)程、多線程、協(xié)程,在不考慮大并發(fā)性能測(cè)試的前提下使用了多線程-線程池的形式實(shí)現(xiàn)。使用的是

concurrent.futures模塊。當(dāng)前僅方便支持webservice接口。


# -*- coding:utf-8 -*-
 
import requests
from concurrent.futures import ThreadPoolExecutor
from Tools.Config import Config # 配置文件讀取
from Tools.Log import Log # 日志管理
from Tools.tools import decoLOG # 日志裝飾
 
'''
  功能:   Requests類
  使用方法: 
  作者:   郭可昌
  作成時(shí)間: 20180224
  更新內(nèi)容:
  更新時(shí)間:
'''
class Requests(object):
  def __init__(self):
    self.session = requests.session()
    self.header = {}
    # URL默認(rèn)來源于配置文件,方便不同測(cè)試環(huán)境的切換,也可以動(dòng)態(tài)設(shè)定
    self.URL = Config().getURL()
    # 默認(rèn)60s,可以動(dòng)態(tài)設(shè)定
    self.timeout = 60
    #http連接異常的場(chǎng)合,重新連接的次數(shù),默認(rèn)為3,可以動(dòng)態(tài)設(shè)定
    self.iRetryNum = 3
 
    self.errorMsg = ""
    # 內(nèi)容 = {用例編號(hào):響應(yīng)數(shù)據(jù)}
    self.responses = {}
    # 內(nèi)容 = {用例編號(hào):異常信息}
    self.resErr={}
 
 
  # 原始post使用保留
  # bodyData: request's data
  @decoLOG
  def post(self, bodyData):
    response = None
    self.errorMsg = ""
 
    try:
      response = self.session.post(self.URL, data=bodyData.encode('utf-8'), headers=self.header, timeout=self.timeout)
      response.raise_for_status()
    except Exception as e:
      self.errorMsg = str(e)
      Log().logger.error("HTTP請(qǐng)求異常,異常信息:%s" % self.errorMsg)
    return response
 
 
  # 復(fù)數(shù)請(qǐng)求并發(fā)處理,采用線程池的形式,用例數(shù)>線程池的容量:線程池的容量為并發(fā)數(shù),否則,用例數(shù)為并發(fā)數(shù)
  # dicDatas: {用例編號(hào):用例數(shù)據(jù)}
  @decoLOG
  def req_all(self, dicDatas, iThreadNum=5):
 
    if len(dict(dicDatas)) < 1:
      Log().logger.error("沒有測(cè)試對(duì)象,請(qǐng)確認(rèn)后再嘗試。。。")
      return self.responses.clear()
 
    # 請(qǐng)求用例集合轉(zhuǎn)換(用例編號(hào),用例數(shù)據(jù))
    seed = [i for i in dicDatas.items()]
    self.responses.clear()
 
    # 線程池并發(fā)執(zhí)行,iThreadNum為并發(fā)數(shù)
    with ThreadPoolExecutor(iThreadNum) as executor:
      executor.map(self.req_single,seed)
 
    # 返回所有請(qǐng)求的響應(yīng)信息({用例編號(hào):響應(yīng)數(shù)據(jù)}),http連接異常:對(duì)應(yīng)None
    return self.responses
 
  # 用于單用例提交,http連接失敗可以重新連接,大重新連接數(shù)可以動(dòng)態(tài)設(shè)定
  def req_single(self, listData, reqType="post", iLoop=1):
    response = None
    # 如果達(dá)到大重連次數(shù),連接后提交結(jié)束
    if iLoop == self.iRetryNum:
      if reqType == "post":
        try:
          response = requests.post(self.URL, data=listData[1].encode('utf-8'), headers=self.header,
                       timeout=self.timeout)
          response.raise_for_status()
        except Exception as e:
          # 異常信息保存只在大連接次數(shù)時(shí)進(jìn)行,未達(dá)到大連接次數(shù),異常信息為空
          self.resErr[listData[0]] = str(e)
          Log().logger.error("HTTP請(qǐng)求異常,異常信息:%s【%d】" % (str(e), iLoop))
 
        self.responses[listData[0]] = response
      else:
        # for future: other request method expand
        pass
    # 未達(dá)到大連接數(shù),如果出現(xiàn)異常,則重新連接嘗試
    else:
      if reqType == "post":
        try:
          response = requests.post(self.URL, data=listData[1].encode('utf-8'), headers=self.header,
                       timeout=self.timeout)
          response.raise_for_status()
        except Exception as e:
          Log().logger.error("HTTP請(qǐng)求異常,異常信息:%s【%d】" % (str(e), iLoop))
          # 重連次數(shù)遞增
          iLoop += 1
          # 進(jìn)行重新連接
          self.req_single(listData, reqType, iLoop)
          # 當(dāng)前連接終止
          return None
        self.responses[listData[0]] = response
      else:
        # for future: other request method expand
        pass
 
  # 設(shè)定SoapAction, 快捷完成webservice接口header設(shè)定
  def setSoapAction(self, soapAction):
    self.header["SOAPAction"] = soapAction
    self.header["Content-Type"] = "text/xml;charset=UTF-8"
    self.header["Connection"] = "Keep-Alive"
    self.header["User-Agent"] = "InterfaceAutoTest-run"
 

當(dāng)前題目:python對(duì)于requests的封裝方法詳解-創(chuàng)新互聯(lián)
瀏覽地址:http://bm7419.com/article48/hssep.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站策劃、自適應(yīng)網(wǎng)站、靜態(tài)網(wǎng)站、網(wǎng)站制作微信小程序、面包屑導(dǎo)航

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都app開發(fā)公司