[Twisted-Python] Using Deferred.called to distinguish between synchronous and asynchronous result
Maciej Wasilak
wasilak at gmail.com
Wed Aug 29 13:53:59 MDT 2012
Hello,
I am implementing UDP-based protocol in Twisted (CoAP) which allows two
behaviors when answering requests:
1. If response is immediately available - send acknowledgement and response
in a single datagram (piggyback response)
2. If response needs to be fetched or prepared - send datagram with
acknowledgement, and then send another datagram with a response (separate
response)
(I think behavior #1 is called synchronous in most Twisted tutorials, and
behavior #2 is called asynchronous.)
When programmer is implementing his application on top of CoAP protocol, he
or she needs to choose how his request handler is going to behave. I would
like to handle both behaviors in the same manner - by forcing every
user-written request handler to return Deferred. Then I would
check Deferred.called parameter.
1. If True - callback will execute immediately and send proper ACK+Response
(that means request handler used defer.succeed() or somethin similar)
2. If False I send empty ACK, and wait for callback to send Response
code:
def respond(request):
d = requestHandler(request)
if d.called is False:
sendEmptyAck()
d.addCallback(sendResponse)
I assume that sendResponse can send either ACK+RSP, or only RSP.
I would like to ask if this is a proper approach?
Best Regards
Maciej Wasilak
-------------- next part --------------
An HTML attachment was scrubbed...
URL: </pipermail/twisted-python/attachments/20120829/c47e1736/attachment-0001.html>
More information about the Twisted-Python
mailing list