From cef9cf926eb9868f59f2d26552018c4310a869bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johnny=20Miller=20=28=E9=94=BA=E4=BF=8A=29?= Date: Wed, 10 Nov 2021 15:54:50 +0800 Subject: [PATCH] perf($email): only login and logout from the email server once --- home_guardian/message/email.py | 22 +++++++++++++++++----- home_guardian/opencv/face_detection.py | 1 - 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/home_guardian/message/email.py b/home_guardian/message/email.py index 25aa081..0db3c65 100644 --- a/home_guardian/message/email.py +++ b/home_guardian/message/email.py @@ -7,6 +7,7 @@ from loguru import logger +from home_guardian.common.debounce_throttle import debounce from home_guardian.configuration.application_configuration import application_conf from home_guardian.template.html_template import render_template @@ -18,6 +19,12 @@ ) _receivers: List[str] = application_conf.get_list("email.receivers") +# Login to the email server +_smtp: smtplib.SMTP = smtplib.SMTP(_mail_host, 25) +_smtp.connect(_mail_host, 25) +_smtp.login(_sender, _mail_password) +logger.warning(f"Logged in to the email server: {_mail_host}") + def build_message( subject: str, @@ -55,6 +62,7 @@ def build_message( return message +@debounce(30) def send_email( subject: str, template_name: str, render_dict: dict, picture_path: str ) -> None: @@ -66,19 +74,23 @@ def send_email( :param render_dict: The render dict for the template. :param picture_path: The path to the picture to attach. """ - smtp: smtplib.SMTP = smtplib.SMTP(_mail_host, 25) - smtp.connect(_mail_host, 25) - smtp.login(_sender, _mail_password) for receiver in _receivers: message: MIMEMultipart = build_message( subject, receiver, template_name, render_dict, picture_path ) logger.debug(f"Sending email. receiver: {receiver}") try: - smtp.sendmail(_sender, [receiver], message.as_string()) + _smtp.sendmail(_sender, [receiver], message.as_string()) logger.debug( f"Sent email successfully. Receiver: {receiver}, subject: {subject}, template_name: {template_name}" ) except smtplib.SMTPException: logger.exception("Exception occurred while sending email!") - smtp.quit() + + +def cleanup() -> None: + """ + Closes the connection to the email server. + """ + _smtp.quit() + logger.warning(f"Logged out from the email server: {_mail_host}") diff --git a/home_guardian/opencv/face_detection.py b/home_guardian/opencv/face_detection.py index 177d171..8eb73be 100644 --- a/home_guardian/opencv/face_detection.py +++ b/home_guardian/opencv/face_detection.py @@ -69,4 +69,3 @@ def async_save_capture(frame) -> None: render_dict, detected_face.picture_path, ) - logger.info("Sent `security_warning` successfully")