在Django中为用户安排电子邮件报告的最佳方法
因此,这个问题主要针对Django的最佳做法和建议。
So this question is focused more around best practice and advice for Django.
本质上,我想安排有关Django的电子邮件报告在以下两个事件上触发:
Essentially, I want to schedule email reports on Django to be triggered on two events:
- 每周报告包含某些统计信息,新闻等的电子邮件
- 在系统中发生事件时触发的报告(即
是否应该通过计划任务直接在Django中完成?还是有其他工具可以使用?
Should this be done directly in Django through scheduled tasks? Or are there any other tools one could use?
关于每周安排的任务,最直接的方法可能是创建一个新的自定义管理命令,并通过cron或Windows Task Scheduler调用该命令。实际上,这里已经有了答案,还有其他可供您考虑的选项:
Regarding a weekly scheduled task, the most straightforward approach might be to create a new custom management command, and have a cron or Windows Task Scheduler call that command. This actually already has an answer here, along with other possible options for you to consider:
注意:如果您使用的是virtualenv,确保cron通过virtualenv中的 python
二进制文件而不是系统路径中的二进制文件来调用管理命令。
Note: If you're using a virtualenv, make sure to have the cron call the management command via the python
binary in the virtualenv, not the one in the system path.
对于基于应用程序事件或条件的触发操作,有两个想法:
As for a triggered action based on an application event or condition, two thoughts:
- You could set up a listener for a post-save signal on your model. When the signal is received, the email could be sent via the receiver. You can read up on signals here.
- Django's send_mail email wrapper is straightforward enough that you could also use that directly in your view.