在Django中,我如何在后台运行一个函数

时间:2015-05-28 15:41:35

标签: python django multithreading background-process

我希望在发布文章时,通过Django中的send_mail()向表格中的所有用户发送电子邮件。我想知道如何通过调用我的文章发布函数中的另一个函数来完成这项工作,该函数可以在后台或另一个线程中执行此任务,以便我的发布函数可以发布文章,并且调用发送电子邮件的函数可以执行背景中的任务。

1 个答案:

答案 0 :(得分:0)

您可以通过创建自定义HttpResponse对象来执行此操作:

from django.http import HttpResponse

# use custom response class to override HttpResponse.close()
class HttpResponseAndMail(HttpResponse):
    def __init__(self, article="", people=[], *args, **kwargs):
        super(HttpResponseAndMail, self).__init__(*args, **kwargs)
        self.article = article
        self.people = people

    def close(self):
        super(HttpResponseAndMail, self).close()
        # do whatever you want, this is the last codepoint in request handling
        if self.status_code == 200:
            send_mail(subject="", from_email="", message=self.article, recipient_list=self.people)

此代码在同一个python线程中运行,但只有在其他所有内容完成后才会运行,因此不会减慢您的Web服务器速度。

相关问题