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

2024-04-19 15:12:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: django函数用户send电子邮件文章mail线程
1条回答
网友
1楼 · 发布于 2024-04-19 15:12:13

您可以通过创建自定义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服务器的速度。在

相关问题 更多 >