发送email邮件带附件,编写装饰器实现python请求错

2019-10-18 06:31 来源:未知

 

在做接口自动化测验的时候,总会境遇,因接二连三超时等不当变成,接口脚本退步。

类继承:

EMAIL功用落成:

合法给出的诀要:

连续的主张在于,充份利用已有类的效应,在其基础上来增加来定义新的类。

1.发送EMAIL带附属类小部件,况兼带压缩文件夹做为附属类小部件

max_retries=5 出错重试5次
注意的是,这个只对DNS,连接错误进行重试。

    from requests.adapters import HTTPAdapter
    s = requests.Session()
    s.mount('http://',HTTPAdapter(max_retries=5))
    s.mount('https://',HTTPAdapter(max_retries=5))
    s.get('https://www.baidu.com')

 

#_*_coding:utf-8_*_

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.header import Header
from email import encoders
import time
import yaml,os,base64
from pos.lib import gl,scripts


class EmailClass(object):
    def __init__(self):
        self.curDateTime = str(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())) #当前日期时间
        self.config = scripts.getYamlfield(gl.configFile) #配置文件路径
        self.sender = self.config['EMAIL']['Smtp_Sender'] # 从配置文件获取,发件人
        self.receivers = self.config['EMAIL']['Receivers']  # 从配置文件获取,接收人
        self.msg_title = self.config['EMAIL']['Msg_Title'] #从配置文件获取,邮件标题
        self.sender_server = self.config['EMAIL']['Smtp_Server'] #从配置文件获取,发送服务器
        self.From = self.config['EMAIL']['From']
        self.To = self.config['EMAIL']['To']

    '''
    配置邮件内容
    '''
    @property
    def setMailContent(self):
        print self.receivers
        msg = MIMEMultipart()
        msg['From'] = Header(self.From,'utf-8')
        msg['To'] = self.To
        msg['Subject'] = Header('%s%s'%(self.msg_title,self.curDateTime),'utf-8')

        #附件路径
        dirpath = gl.reportPath
        zipfile = os.path.join(os.path.dirname(dirpath), 'report.zip')
        reportfile = os.path.join(gl.reportPath, 'Report.html')
        scripts.zipDir(dirpath,zipfile) #压缩报告
        #增加邮件内容为html
        fp = open(reportfile, 'rb')
        reportHtmlText = fp.read()
        msg.attach(MIMEText(reportHtmlText,'html','utf-8'))
        fp.close()

        #增加附件
        html = self.addAttach(zipfile,filename='Report%s.zip'%self.curDateTime) #自动化测试报告附件
        msg.attach(html)

        return msg


    '''
    增加附件
    '''
    def addAttach(self,apath,filename='Report.html'):
        with open(apath, 'rb') as fp:
            attach = MIMEBase('application','octet-stream')
            attach.set_payload(fp.read())
            attach.add_header('Content-Disposition', 'attachment', filename=filename)
            encoders.encode_base64(attach)
            fp.close()
            return attach


    '''
    发送电子邮件
    '''
    def sendEmail(self,message):
        try:
            smtpObj = smtplib.SMTP()
            smtpObj.connect(self.sender_server,25)
            smtpObj.login(self.sender,self.config['EMAIL']['Password'])
            smtpObj.sendmail(self.sender,self.receivers , message.as_string())
            smtpObj.quit()
            print "邮件发送成功"
        except smtplib.SMTPException as ex:
            print "Error: 无法发送邮件.%s"%ex

    #发送调用
    @property
    def send(self):
        self.sendEmail(self.setMailContent)

if __name__=="__main__":
    EmailClass().send

 

Parent Class(父类) 与 Child Class(子类):

 

 

被连续的类称为父类,承继的类称为子类,一个父类,能够有多少个子类;

2.压缩文件夹及文件代码:

自编写装饰器一

子类,一旦三回九转父类,就具有了父类的习性与措施,依据须要能够拓宽增加和删除改。

def zipDir(dirpath,outFullName):
    """
    压缩指定文件夹
    :param dirpath: 目标文件夹路径
    :param outFullName: 压缩文件保存路径+xxxx.zip
    :return: 无
    """
    zip = zipfile.ZipFile(outFullName,"w",zipfile.ZIP_DEFLATED)
    for path,dirnames,filenames in os.walk(dirpath):
        # 去掉目标跟路径,只对目标文件夹下边的文件及文件夹进行压缩
        fpath = path.replace(dirpath,'')

        for filename in filenames:
            zip.write(os.path.join(path,filename),os.path.join(fpath,filename))
    zip.close()
from requests.exceptions import ConnectionError
import requests
def retry(**kw):
    def war(func):
        def w(*args,**kwargs):
            try:
                ret = func(*args,**kwargs)
            except ConnectionError:
                kw['reNum'] = int(kw['reNum']) - 1
                if kw['reNum'] >=0:
                    print kw['reNum']
                    ret = w(*args,**kwargs)
                else:
                    ret = ConnectionError
            return ret
        return w
    return war

这种做法的首要性受益之一就是代码重用。

 

 

 

3.安排文件config.yaml

自编写装饰器二

演示代码1:

TAG标签:
版权声明:本文由澳门金莎娱乐网站发布于澳门金莎唯一指定官网,转载请注明出处:发送email邮件带附件,编写装饰器实现python请求错