[Twisted-Python] help using deferred

Jean-Paul Calderone exarkun at divmod.com
Mon May 11 09:29:52 EDT 2009

On Mon, 11 May 2009 12:24:54 +0200, Luigi Conte <luigiandcosolutions at gmail.com> wrote:
>Hi people,
>I'm luigi and I'm a student at Politecnico di Milano, Italy. I'm working for
>a graduate thesis on a framework called usher. It provides an API to do
>connect e command operations. It manages all those calls with a defferred
>object (i think). In fact when I call the connect it returns me a defferred
>object. All that i want to know is how to call the other operations with
>this object and how to know when an operation is completely done.
>The procedure I call is simple: connect method, start method many times,
>stop method, disconnect method. I want to call these methods sequentially
>because I have to fallow a list of commands so I have to be sure the
>previous methods are already been invoked. I'll post the main methods hoping
>someone could help me in how to add the method in the deferred and how to
>know when it is completely invoked.

The Deferred tells you two things.  It tells you when an operation has
completed and it tells you the result of the operation.  It tells you
*when* by calling your callback function at that time.  It tells you
what *result* by the value it passes to that callback function.

So if you want to connect, then do the "start" operation many times, then
stop, then disconnect, you have some Deferreds and a simple recursion-
or loop-like structure.  For example,

    # First, set up the connection.
    taskDeferred = connect(...)
    def cbConnected(connectResult):
        # This function will run once the Deferred returned by `connect´
        # fires.  Here, "start" something.
        return start(...)

    def cbStarted(startResult):
        # Now the Deferred returned by `start´ has fired.
        if someStopCondition:
            # If we decide it is time to stop, then stop.
            return stop(...)
        # Otherwise, run `start´ again
        startAgainDeferred = start(...)
        # And call this callback again with this new call's result.
        return startAgainDeferred

    def cbStopped(stopResult):
        # The only exit from the earlier "loop" is through the code path
        # which calls `stop´.  This callback is called when the Deferred
        # returned by that call fires.  Do the disconnect now.
        return disconnect(...)

    def cbDisconnected(disconnectResult):
        print "All done"

    # It's possible something will go wrong in the above.  To make sure any
    # exceptions are reported, add a logging errback at the very end to
    # display whatever might go wrong.

Hope this helps,


More information about the Twisted-Python mailing list