Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python twisted Reactor class

Tags:

python

twisted

What is the significance of the decorators

 @reactor.callWhenRunning,
 @results_deferred.addCallback
 @results_deferred.addErrback.

Also what are deferred strings, for example in the

 twisted.internet.utils.getProcessOutput()

returns a deferred string what exactly is happening here?

I am new to twisted hence this might be a very simple question but reading twisted documentation did not help me much

like image 856
anijhaw Avatar asked Jan 19 '26 10:01

anijhaw


1 Answers

In the normal programming practice you'd do

db = Database.connect()
result = db.getResult()
processResult(result)

Now depending on your Database and network, these 3 statements can take anywhere from a millisecond to a few seconds.

We've all been programming this way for decades now, and for the most part we're fine with 'waiting'.

But there comes a time when your program cant just wait for results. You'd start to think, gee I could do a lot of other things while I wait for the result. Maybe print an output, or process a function, or just quickly check the socket etc.

Enter Twisted and Deferred.

Instead of waiting for result, in Twisted when invoked the special methods you'll get a Deferred. You'll add a callback function to this deferred which means, call this function when you have the result/answer.

deferredResult = db.nonBlockingGetResult()
deferredResult.addCallback(processOutput)

As soon as the first statement is executed, it returns the 'something' back. And that something is Deferred. There's no blocking there, there no waiting. And to this Deferred you add the callback processOutput which is called when deferred is 'fired' - ie result is ready.

HTH

like image 53
Jeffrey Jose Avatar answered Jan 22 '26 00:01

Jeffrey Jose