[Twisted-Python] unblocking smtp send?

glyph at divmod.com glyph at divmod.com
Thu Jul 3 16:45:45 EDT 2008

On 06:01 pm, k7lim at cs.stanford.edu wrote:
>My webapp is blocking on this sendmail code that I wrote:
>        reactor.run(installSignalHandlers=0)

>Is there any way I can allow the UI to continue, without blocking on
>this code?  According to the logs, there was a 30second cap between
>starting factory and stopping:

Answering this question correctly will depend a great deal on the 
specifics of your web application's architecture and deployment.

If your web application is itself a twisted application (i.e. you are 
using twisted.web) then the reactor should already be running, and you 
shouldn't start it up.  The send won't block.

If you're using a multi-threaded deployment environment, then you can't 
safely use Twisted APIs, let alone run the reactor, from multiple 
threads, so you need to investigate some other way of sending mail from 
your application.  Having one thread run the twisted loop and doing a 
callFromThread with the function which sends mail might be the right 
thing to do.

If you're running in a CGI-style execution environment, where there are 
multiple processes but one thread per process... depending on the 
specifics of your server environment you might be able to spawn a 
subprocess to do the Twisted work and wait for it at the very end of 
your script rather than blocking in the middle, or even leave it to run 
past the end of your script.  Reporting errors to the user would be 
pretty tricky in this case though.

Whatever your decision, you should try to move the call to reactor.run() 
as far away from application code as possible.  You should not have a 
function which sends mail and then immediately calls reactor.run() 
because then it won't work in a running reactor, which should be the 
"normal" case for pretty much any code which uses Twisted.

More information about the Twisted-Python mailing list