在我的下面的代码中,我传递了一个host:端口组合,并尝试使用twisted Deferred从服务器获取一些信息。我已经展示了我想要做的非常基本的代码。与主机端口的连接是通过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()
答案 0 :(得分:1)
问题是你假设conn.request
(在第17行)会引发httplib.HTTPException
,但这不是它引发的异常类型。由于您并不十分清楚会引发什么异常,因此我建议您制作一条except...
语句并从sys.exc_info()
获取异常数据。
按照以下方式修复:
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:
self.d.errback(sys.exc_info())
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()