在下面的代码中,我传递了一个主机:端口组合,并尝试使用扭曲延迟从服务器获取一些信息。我已经展示了我正在尝试做的一个非常基本的代码。与主机端口的连接是通过 httplib 建立的。如果主机启动,它可以正常工作。调用正确的回调方法。但是当它失败时(当检索 url 失败时),它不会进入 printError 函数。我收到“延迟中的未处理错误”错误并且循环停止。有人可以告诉我如何摆脱错误。请提供解决方案。
import httplib, time, sys
from twisted.internet import reactor, defer, task
from twisted.python import log
class Getter:
def gotResults(self, x):
( host, port ) = x.split(":")
conn = httplib.HTTPConnection( host, port )
try :
conn.request ( 'GET', '/get/data/' )
response = conn.getresponse()
self.d.callback ( response )
except ( httplib.HTTPException ) :
self.d.errback(ValueError("Error Connecting"))
def getDummyData(self, x):
currTime = time.strftime( "%H:%M:%S" )
print currTime
self.d = defer.Deferred()
self.gotResults(x)
return self.d
def printData(data):
for d in data:
print "Results %s %s" % ( str(d[1].status), str(d[1].reason) )
def printError(data):
print data
def testmessage():
# this series of callbacks and errbacks will print an error message
g = Getter()
deferred1 = g.getDummyData( 'valid_hostname1:port1' )
# this should go to printData
g = Getter()
deferred2 = g.getDummyData('invalid_hostname2:port2')
# this should go to printError
d1 = defer.DeferredList ( [ deferred1, deferred2 ] )
d1.addCallback ( printData )
d1.addErrback ( printError )
x = task.LoopingCall ( testmessage )
x.start ( 1 )
reactor.callLater(300, reactor.stop);
reactor.run()