[Twisted-Python] Converting async to sync code (blocking until deferreds fire)

Barry Wark barrywark at gmail.com
Mon Jul 21 12:10:07 EDT 2008


You might take a look at
twisted.internet.threads.blockingCallFromThread (version >=8.0, I
believe). I realize that it's not the favored solution by many of the
Twisted developers, but it's used succesfully in the IPython project
(which is where I came across it) to create the impression of a
blocking client on top of non-blocking Twisted code.

Barry

On Mon, Jul 21, 2008 at 3:19 AM, Jack Whitham <jack-tp at cs.york.ac.uk> wrote:
>
> Hi,
>
> What is the best way to convert asynchronous code (non-blocking,
> returning deferreds) to synchronous code (blocking)?
>
> I have a client that is written using Twisted. Most of the methods
> within the client object return Deferreds because they send messages
> to a server and replies may take some time. This is ideal for the
> wxwidgets GUI that was originally intended to use the client. But
> now I want to write test scripts for the server that are synchronous.
>
> For example, the client provides the method "GetBitInfo" which returns
> a deferred. The deferred is called back with a list as its parameter
> after the server responds to a request. I would like to be able to
> do something like this:
>
>> def GotBitInfo(l): pass
>>
>> if __name__ == "__main__":
>>     c = Client()
>>
>>     d = c.GetBitInfo()
>>     d.addCallback(GotBitInfo)
>>     waitForDeferred(d)
>>
>>     d = c.DoSomethingElse()
>
> In other words, how do I waitForDeferred(), i.e. block until a Deferred fires?
>
> Of course I could rewrite my script as asynchronous code; but what I
> really want is a simple Python-like interface for the client code
> in order to make things as simple as possible for other users. I don't
> want them to *have* to learn how to write asynchronous code - I want
> it to be optional. If the snippet of code listed above is possible,
> then I can wrap the client methods with code that waits for deferreds
> to fire, then returns the values they were called with. Then the users
> will have two ways to use the code: asynchronous (for GUIs, proxy
> servers, etc.) and synchronous (for test scripts).
>
> I noticed that there is a _wait method in your trial code that seems to
> do what I want, but it looks complicated and I'm not sure it is the
> right answer. Its predecessor was also deprecated, which is a bad
> sign (looks like "do not do this!!"). Hence I am looking for expert
> advice.
>
> Thanks.
>
>
> --
> Jack Whitham
> jack at cs.york.ac.uk
>
>
> _______________________________________________
> Twisted-Python mailing list
> Twisted-Python at twistedmatrix.com
> http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python
>




More information about the Twisted-Python mailing list