简体   繁体   中英

Using try-except sentenec in python with tenacity doesn't retry as expected

Hi there i'm trying to use tenacity for sending an email, the script is the following:

from tenacity import retry, stop_after_attempt
from smtplib import SMTP_SSL, SMTP

@retry(stop = stop_after_attempt(7))
def email_tables(mails_to_list, smtp_host, smtp_port, smtp_user, smtp_pass, tables):

    try:
            #ENVIO DE DATOS

            #Lista de mails a enviar la info
            mails_to = mails_to_list
            msg = (f"From: {smtp_user}\r\nSubject: Daily app status\r\nTo: %s\r\n\r\n" % (", ".join(mails_to)))

            for table in tables:
                msg = msg + table + "\r\n\r\n"

            print(msg)

            with SMTP(host = smtp_host, port = smtp_port) as smtp:
                smtp.starttls()
                smtp.login(user = smtp_user, password = smtp_pass)
                smtp.sendmail(from_addr = smtp_user, to_addrs = mails_to, msg = msg)
                smtp.quit()

    except Exception:
        print(Exception)

The thing is that if i run email_tables(vars) the output runs only once the method and then exits the script.

If i remove the try-except sentence and don't print the Exception the script runs 7 times as expected and then raises the error.

I don't know what i'm doing wrong here in order for retry to work. Later i would like to save a log in a file when exception is raised, ideally with how many times it failed.

Thanks in advance

Seems that all i needed to do is add a raise sentence with the exception for retry to be able to read it. Final code:

from tenacity import retry, stop_after_attempt
from smtplib import SMTP_SSL, SMTP

@retry(stop = stop_after_attempt(7))
def email_tables(mails_to_list, smtp_host, smtp_port, smtp_user, smtp_pass, tables):

    try:
            #ENVIO DE DATOS

            #Lista de mails a enviar la info
            mails_to = mails_to_list
            msg = (f"From: {smtp_user}\r\nSubject: Daily app status\r\nTo: %s\r\n\r\n" % (", ".join(mails_to)))

            for table in tables:
                msg = msg + table + "\r\n\r\n"

            print(msg)

            with SMTP(host = smtp_host, port = smtp_port) as smtp:
                smtp.starttls()
                smtp.login(user = smtp_user, password = smtp_pass)
                smtp.sendmail(from_addr = smtp_user, to_addrs = mails_to, msg = msg)
                smtp.quit()

    except Exception:
        print(Exception)
        raise(Exception)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM