SHARE
TWEET

Twisted Timeout Etude (with Deferred) 1

a guest Dec 26th, 2012 166 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # A solution to exercise 1 of the Twisted tutorial at http://krondo.com/blog/?p=1778
  2.  
  3. # class PoetryProtocol is the only thing changed from get-poetry client 4.0
  4.  
  5. class PoetryTimeoutError(Exception): pass
  6.  
  7. class PoetryProtocol(Protocol):
  8.  
  9.     poem = ''
  10.  
  11.     def connectionMade(self):
  12.         port = self.transport.getPeer().port
  13.         self.onTime = None
  14.         # poetry downloads on even numbered ports time out after 1 sec
  15.         # just another of the ways the universe is stacked against poetry
  16.         if not port % 2:
  17.             self.onTime = True
  18.             from twisted.internet import reactor
  19.             self.timer = reactor.callLater(1, self.timeout)
  20.  
  21.     def timeout(self):
  22.         self.onTime = False
  23.         self.transport.loseConnection()
  24.  
  25.     def dataReceived(self, data):
  26.         self.poem += data
  27.  
  28.     def connectionLost(self, reason):
  29.         if self.onTime is not None:
  30.             if self.onTime == True:
  31.                 self.timer.cancel()
  32.             else:
  33.                 err = PoetryTimeoutError('Evil timeout stole your poetry again!')
  34.                 self.factory.deferred.errback(Failure(err))
  35.                 return
  36.         self.poemReceived(self.poem)
  37.  
  38.     def poemReceived(self, poem):
  39.         self.factory.poem_finished(poem)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top