I want someone's that worked with celery before to take a look at my tasks here and see if it's efficient, everything is working but I want to make sure that am not messing it up:
tasks.py:
@shared_task
def send_notification_email(email_to, respond, producer):
user = get_user_model().objects.get(email=email_to)
subject = 'You have notifications'
user_name = user.username
html_template = 'project/emails/notification_email.html'
context = {
'username' : user_name,
'respond': respond,
'producer': producer
}
task_chain = chain(
encode_image.s(),
send_email.s(email_to, subject, html_template, context)
)
# execute the task chain
task_chain.delay()
@shared_task
def encode_image():
# MUST EDIT IN PRODUCTION
image_path = os.path.join(settings.BASE_DIR, 'static', 'img', 'email_logo.jpg')
# encode the image file
with open(image_path, "rb") as image_file:
encoded_image = base64.b64encode(image_file.read()).decode("utf-8")
return encoded_image
@shared_task(bind=True, max_retries=2)
def send_email(self, encoded_image, to_email, subject, html_template, context):
try:
# add the encoded image to the context
context['logo_base64'] = encoded_image
# render email template with provided context
html_content = render_to_string(html_template, context)
text_content = strip_tags(html_content)
msg = EmailMultiAlternatives(subject, text_content, settings.DEFAULT_FROM_EMAIL, [to_email])
msg.attach_alternative(html_content, "text/html")
msg.send()
except Exception as exc:
# retry the task twice in case of failure
raise self.retry(exc=exc)
celery server:
celery -A project_name worker -l INFO --without-gossip --without-mingle --without-heartbeat -Ofair --pool=solo