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

In Django, how can I run a function in background

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

您可以通过创建自定义 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 线程中,但仅在其他所有内容都完成后才执行,因此不会减慢您的网络服务器。