[Twisted-Python] blocking question
andrew-twisted at puzzling.org
Thu Apr 17 23:43:11 EDT 2003
On Thu, Apr 17, 2003 at 11:15:06PM -0400, Konrad Rokicki wrote:
> Hey everyone, newbie question:
> Are there any Python/Twisted idioms for doing blocking? More specifically,
> in a client I have a method to send a query to the server and another
> method that gets called when the query is answered. Is there an easy way
> to say "send the query then wait x seconds for it to return in this
> It seems like blocking is taboo in twisted and if anyone has an
> alternative I'd be glad to hear it. I guess I could do this
> asynchronically but it would be a pain I think.
This is what Deferreds are for. Your client should look something like
from twisted.internet.defer import Deferred
from twisted.protocols.basic import LineReceiver
"""A very simple protocol that sends one line 'queries', and
receives one line answers in response. An answer that startswith
'Result:' is considered a successful response; anything else is an
self.queryDeferred = Deferred()
self.queryDeferred = None
This is obviously a rather stupid protocol.
Then, to perform a query:
# Assume we've already got a connected MyClient instance in the variable
# Define a callback and an errback.
def printResult(result, query):
print 'Result of query %r is: %r' % (query, result)
def printFailure(failure, query):
print 'Query %r failed:' % query
# Send the query
query = 'query string'
deferred = myclient.sendQuery(query)
# Set a timeout
# Attach callback/errback to handle the result
See http://twistedmatrix.com/documents/howto/defer for more details on using
Deferreds. See also the "Writing a Server" and "Writing a Client" howtos.
This is pretty basic Twisted stuff, so the existing docs cover it pretty
More information about the Twisted-Python