Django models, signals and email sending delay

我们两清 提交于 2019-12-11 04:08:03

问题


I have added a signal to my model, which sends email to some email addresses once a model is saved (via models.signals.post_save.connect signal and send_mail for email sending). This idea still makes delay for the users, when they save the model at the site, they have to wait until all those emails are sent and thats when they receive response from the server.

Before trying signals, I had tried to wrap the save method of my model, and after super(Foo, self).save(*args, **kwargs) I was sending emails. This delay experience was happening with that method too.

I simply want my email sending actions to be done in background, without showing delays to users at site.

How can this be solved?


回答1:


The easiest thing is to queue the email messages and then have them sent by a daemon. Check out django-mailer.

Since you only seem to be concerned with send_mail, you can get started with two steps. First, use this to import django-mailer's version of send_mail:

# favour django-mailer but fall back to django.core.mail
from django.conf import settings

if "mailer" in settings.INSTALLED_APPS:
    from mailer import send_mail
else:
    from django.core.mail import send_mail

And then create a cronjob that calls manage.py send_mail to send the mail. Check the django-mailer usage docs for example cronjob entries.

If you are not seeing any email get sent, try running manage.py send_mail on the console. This seems to be the number one problem people have.




回答2:


To avoid a delay to the response, you want to do this asynchronously in another process.

This question is about how to handle that: Advice on Python/Django and message queues



来源:https://stackoverflow.com/questions/2349483/django-models-signals-and-email-sending-delay

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!