python对于requests的封装方法详解


Posted in Python onJanuary 03, 2019

由于requests是http类接口的核心,因此封装前考虑问题比较多:

1. 对多种接口类型的支持;

2. 连接异常时能够重连;

3. 并发处理的选择;

4. 使用方便,容易维护;

当前并未全部实现,后期会不断完善。重点提一下并发处理的选择:python的并发处理机制由于存在GIL的原因,实现起来并不是很理想,综合考虑多进程、多线程、协程,在不考虑大并发性能测试的前提下使用了多线程-线程池的形式实现。使用的是

concurrent.futures模块。当前仅方便支持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类
  使用方法: 
  作者:   郭可昌
  作成时间: 20180224
  更新内容:
  更新时间:
'''
class Requests(object):
  def __init__(self):
    self.session = requests.session()
    self.header = {}
    # URL默认来源于配置文件,方便不同测试环境的切换,也可以动态设定
    self.URL = Config().getURL()
    # 默认60s,可以动态设定
    self.timeout = 60
    #http连接异常的场合,重新连接的次数,默认为3,可以动态设定
    self.iRetryNum = 3
 
    self.errorMsg = ""
    # 内容 = {用例编号:响应数据}
    self.responses = {}
    # 内容 = {用例编号:异常信息}
    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请求异常,异常信息:%s" % self.errorMsg)
    return response
 
 
  # 复数请求并发处理,采用线程池的形式,用例数>线程池的容量:线程池的容量为并发数,否则,用例数为并发数
  # dicDatas: {用例编号:用例数据}
  @decoLOG
  def req_all(self, dicDatas, iThreadNum=5):
 
    if len(dict(dicDatas)) < 1:
      Log().logger.error("没有测试对象,请确认后再尝试。。。")
      return self.responses.clear()
 
    # 请求用例集合转换(用例编号,用例数据)
    seed = [i for i in dicDatas.items()]
    self.responses.clear()
 
    # 线程池并发执行,iThreadNum为并发数
    with ThreadPoolExecutor(iThreadNum) as executor:
      executor.map(self.req_single,seed)
 
    # 返回所有请求的响应信息({用例编号:响应数据}),http连接异常:对应None
    return self.responses
 
  # 用于单用例提交,http连接失败可以重新连接,最大重新连接数可以动态设定
  def req_single(self, listData, reqType="post", iLoop=1):
    response = None
    # 如果达到最大重连次数,连接后提交结束
    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:
          # 异常信息保存只在最大连接次数时进行,未达到最大连接次数,异常信息为空
          self.resErr[listData[0]] = str(e)
          Log().logger.error("HTTP请求异常,异常信息:%s【%d】" % (str(e), iLoop))
 
        self.responses[listData[0]] = response
      else:
        # for future: other request method expand
        pass
    # 未达到最大连接数,如果出现异常,则重新连接尝试
    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请求异常,异常信息:%s【%d】" % (str(e), iLoop))
          # 重连次数递增
          iLoop += 1
          # 进行重新连接
          self.req_single(listData, reqType, iLoop)
          # 当前连接终止
          return None
        self.responses[listData[0]] = response
      else:
        # for future: other request method expand
        pass
 
  # 设定SoapAction, 快捷完成webservice接口header设定
  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"

以上这篇python对于requests的封装方法详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python正则抓取网易新闻的方法示例
Apr 21 Python
python读写LMDB文件的方法
Jul 02 Python
详解opencv Python特征检测及K-最近邻匹配
Jan 21 Python
Python实战购物车项目的实现参考
Feb 20 Python
python使用pandas处理大数据节省内存技巧(推荐)
May 05 Python
Python自动化运维之Ansible定义主机与组规则操作详解
Jun 13 Python
pyqt5 键盘监听按下enter 就登陆的实例
Jun 25 Python
pyqt5 使用cv2 显示图片,摄像头的实例
Jun 27 Python
Django 开发调试工具 Django-debug-toolbar使用详解
Jul 23 Python
python切片(获取一个子列表(数组))详解
Aug 09 Python
使用OpCode绕过Python沙箱的方法详解
Sep 03 Python
Python基于Tensor FLow的图像处理操作详解
Jan 15 Python
python使用suds调用webservice接口的方法
Jan 03 #Python
Python调用服务接口的实例
Jan 03 #Python
Python2和Python3之间的str处理方式导致乱码的讲解
Jan 03 #Python
python requests 库请求带有文件参数的接口实例
Jan 03 #Python
Python图像处理之颜色的定义与使用分析
Jan 03 #Python
Python在图片中插入大量文字并且自动换行
Jan 02 #Python
python 输出所有大小写字母的方法
Jan 02 #Python
You might like
asp函数split()对应php函数explode()
2019/02/27 PHP
通过Mootools 1.2来操纵HTML DOM元素
2009/09/15 Javascript
javascript预览上传图片发现的问题的解决方法
2010/11/25 Javascript
JavaScript之Getters和Setters 平台支持等详细介绍
2012/12/07 Javascript
如何用js控制frame的隐藏或显示的解决办法
2013/03/20 Javascript
原生JS实现图片轮播与淡入效果的简单实例
2016/08/21 Javascript
Node.js的基本知识简单汇总
2016/09/19 Javascript
JS基于面向对象实现的多个倒计时器功能示例
2017/02/28 Javascript
Vue2 模板template的四种写法总结
2018/02/23 Javascript
vue项目关闭eslint校验
2018/03/21 Javascript
angular4 共享服务在多个组件中数据通信的示例
2018/03/30 Javascript
在vue中使用防抖和节流,防止重复点击或重复上拉加载实例
2019/11/13 Javascript
解决vue初始化项目一直停在downloading template的问题
2020/11/09 Javascript
[03:41]DOTA2上海特锦赛小组赛第三日recap精彩回顾
2016/02/28 DOTA
python中PIL安装简单教程
2016/04/21 Python
Python爬虫代理IP池实现方法
2017/01/05 Python
Python heapq使用详解及实例代码
2017/01/25 Python
python3实现TCP协议的简单服务器和客户端案例(分享)
2017/06/14 Python
[原创]windows下Anaconda的安装与配置正解(Anaconda入门教程)
2018/04/05 Python
使用pandas中的DataFrame数据绘制柱状图的方法
2018/04/10 Python
keras的三种模型实现与区别说明
2020/07/03 Python
python二维图制作的实例代码
2020/12/03 Python
Selenium Webdriver元素定位的八种常用方式(小结)
2021/01/13 Python
CSS3实现红包抖动效果
2020/12/23 HTML / CSS
Html5之webcoekt播放JPEG图片流
2020/09/22 HTML / CSS
澳大利亚牛仔裤商店:Just Jeans
2016/10/13 全球购物
澳大利亚第一的设计师礼服租赁网站:GlamCorner
2017/08/13 全球购物
锐步英国官网:Reebok英国
2019/11/29 全球购物
大三预备党员入党思想汇报
2014/01/08 职场文书
2014学雷锋活动总结
2014/03/09 职场文书
信用卡逾期证明示例
2014/09/13 职场文书
2014年小学德育工作总结
2014/12/05 职场文书
网吧管理制度范本
2015/08/05 职场文书
Python利器openpyxl之操作excel表格
2021/04/17 Python
python正则表达式re.search()的基本使用教程
2021/05/21 Python
基于redis+lua进行限流的方法
2022/07/23 Redis