Šimon Kostolný
Šimon Kostolný

Reputation: 79

Send mails async in web.py

I try to solve problem with sending mails(or any long task) in web.py project. What I want is to start sending any mail and return the http response. But this task (sending) is taking a long time. Is there any solution?

Example:

import web
''some settings urls, etc.''

class Index:
    def GET(self):
        ''task''
        sending_mail()
        return 'response'

I found many examples about async tasks but I think that if this task put to background and return 'response' it will fail.

Upvotes: 1

Views: 670

Answers (2)

kevgathuku
kevgathuku

Reputation: 348

Moving the sending_email() task to a background queue would be the best solution. This would allow you to return the response immediately and get the results of the sending_email task later on.

Let me also suggest taking a look at RQ It is a lightweight alternative to Celery that I find easier to get up and running. I have used it in the past for sending emails in the background and it didn't disappoint.

Upvotes: 0

Thomas Orozco
Thomas Orozco

Reputation: 55207

You could get away with sending email in a separate thread (you can spawn one when you need to send an email):

import threading
threading.Thread(target=sending_email).start()

However, the all-around best (and standard) solution would be to use an asynchronous task processor, such as Celery. In your web thread, simply create a new task, and Celery will asynchronously execute it.


There is no reason why "returning response" would fail when using a message queue, unless your response depends on the email being sent prior to sending the response (but in that case, you have an architectural problem).

Upvotes: 3

Related Questions