Search code examples
pythondjangomultithreadingbackground-process

In Django, how can I run a function in background


I want to send email through send_mail() in Django to all the users in a table when I publish my article. I want to know how can I do this job by calling another function from my article publish function which can perform this task in background or in another thread so that my publish function can publish an article and the function which was called to send email can perform the task in background.


Solution

  • You can do this, by creating a custom HttpResponse-object:

    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)
    

    This code is run in the same python thread, but only after everything else is finished, thus not slowing down your web-server.