django - Django:重定向后发送电子邮件
问题描述
有没有办法在“返回重定向”之后发送电子邮件?
视图.py
选项 1:在 'redirect' 之前放置 'send_mail'
if request.method == 'POST':
formset = TestFormSet(request.POST,request.FILES,instance=project)
if formset.is_valid():
subject = 'Notifications'
html_message = "Testing notifications"
recipient = ["testingemail@gmail.com"]
send_mail(subject, html_message, EMAIL_HOST_USER, [recipient],fail_silently = False)
formset.save()
return redirect("home")
With Option 1, the email is sent successfully but on the front-end the page has to wait until the email is sent before the redirection takes place.
选项 2:在重定向后放置“send_mail”
if request.method == 'POST':
formset = TestFormSet(request.POST,request.FILES,instance=project)
if formset.is_valid():
formset.save()
return redirect("home")
subject = 'Notifications'
html_message = "Testing notifications"
recipient = ["testingemail@gmail.com"]
send_mail(subject, html_message, EMAIL_HOST_USER, [recipient],fail_silently = False)
使用选项 2,保存表单集但不发送电子邮件。有没有办法在重定向后发送电子邮件,以便用户在重定向页面之前不等待电子邮件处理?
谢谢。
解决方案
之后的任何代码return
都不会运行。一种方法是使用像 celery 这样的任务队列并将电子邮件作为后台任务发送。你可以看看django-mailer。这些方法的缺点是您需要维护一个额外的系统。
您可能会看到一些在单独的线程中发送电子邮件的解决方案,但我会避免使用这些解决方案,因为它们可能很脆弱。
推荐阅读
- flutter - 如何修复“已关闭的 Dismissible 小部件仍然是树的一部分。” 颤振错误
- python - 解析 netParameter 文件失败
- c# - how to pass mxgraph generated xml to Action of controller?
- php - 如何知道PHP中异常来自的行号
- mysql - 什么是正确的查询语句?
- php - 如何在laravel中搜索2个日期的特定一条记录?
- animation - 使用 libwebp c api 创建动画,但只编码第一帧
- python-3.x - 如何在 python 中修复“IndentationError:预期有缩进块”
- java - 如何修复 MockitoExtension.class 未解决的错误
- drools - Optaplanner Drools 性能相当慢