基础类封装-Requests库封装

1 #!/usr/bin/env python3 2 # -*- coding: utf-8 -*- 3 # @Time : 2020/03/18 23:37 4 # @Author : Tang Yiwei 5 # @Email : 892398433@qq.com 6 # @File : httprun.py 7 # @Software: PyCharm 8 9 import requests 10 from lib.logger import logger 11 from requests.auth import HTTPBasicAuth 12 from requests.exceptions import ReadTimeout,HTTPError,RequestException 13 try: 14 from requests.packages import urllib3 15 urllib3.disable_warnings() 16 except: 17 import logging 18 logging.captureWarnings(True) 19 20 class HttpRun: 21 22 @staticmethod 23 def http_run(method=None,url=None,data=None,headers=None,files=None,cookies=None,verify=None,cert=None,proxies=None,timeout=20,auth=None): 24 """ 25 :param method:请求的方式,get、post等等 26 :param url: 请求的地址 :post 27 :param data:传递的参数 28 :param headers:传递的请求头 29 :param files:上传的文件,例如files={'file':open('favicon.ico','rb')},传二进制文件 30 :param cookie:请求时传递的cookie值 31 :param verify:是否忽略SSLError,False为忽略,True为显示 32 :param cert:指定证书文件,需要有crt和key文件,并且指定他们的路径,例如cert=('/path/server.crt','/path/key') 33 :param proxies:设置代理,例如proies = {"http":"http://10.10.1.10:3128","https":"http://10.10.1.10:1080"} 34 :param timeout:设置请求的超时时间,连接和读取的总时长,例如timeout=1 35 :param auth:用户认证,auth=HTTPBasicAuth('username','password') 36 :return: 37 """ 38 try: 39 if method.strip().lower() == 'get' or method == None: 40 res = requests.get(url=url,params=data,headers=headers,cookies=cookies,verify=verify,cert=cert,proxies=proxies,timeout=timeout,auth=auth) 41 elif method.strip().lower() == 'post': 42 res = requests.post(url=url,data=data,headers=headers,cookies=cookies,files=files,verify=verify,cert=cert,proxies=proxies,timeout=timeout,auth=auth) 43 else: 44 raise Exception("Unsupported requests") 45 return res 46 except ReadTimeout as e: 47 logger.logger.exception("time out,{0}".format(e)) 48 except HTTPError as e: 49 logger.logger.exception("http error,{0}".format(e)) 50 except RequestException as e: 51 logger.logger.exception("requests error,{0}".format(e)) 52 except Exception as e: 53 logger.logger.exception("other error,{0}".format(e))

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zgdwgw.html