您缺少 Twisted 运作方式的基础知识。这一切都围绕着reactor
,你甚至从来没有运行过。像这样思考反应堆:
(source: krondo.com http://krondo.com/blog/wp-content/uploads/2009/07/reactor-1.png)
在启动反应器之前,通过设置延迟,您所做的就是将它们链接起来,没有任何事件可以触发。
我建议你给扭曲的介绍 http://krondo.com/an-introduction-to-asynchronous-programming-and-twisted/ by 戴夫·佩蒂科拉斯 http://krondo.com/一读。它速度很快,并且确实为您提供了 Twisted 文档所没有的所有缺失信息。
无论如何,这是最基本的用法示例getPage
尽可能:
from twisted.web.client import getPage
from twisted.internet import reactor
url = 'http://aol.com'
def print_and_stop(output):
print output
if reactor.running:
reactor.stop()
if __name__ == '__main__':
print 'fetching', url
d = getPage(url)
d.addCallback(print_and_stop)
reactor.run()
Since getPage
返回延迟,我正在添加回调print_and_stop
到延迟链。之后,我开始reactor
。反应堆起火getPage
,然后触发print_and_stop
它打印来自 aol.com 的数据,然后停止反应器。
编辑以显示 OP 代码的工作示例:
class GrabPage:
def __init__(self, page):
self.page = page
########### I added this:
self.data = None
def start(self, *args):
if args == ():
# We apparently don't need authentication for this
d1 = getPage(self.page)
else:
if len(args) == 2:
# We have our login information
d1 = getPage(self.page, headers={"Authorization": " ".join(args)})
else:
raise Exception('Missing parameters')
d1.addCallback(self.pageCallback)
dl = DeferredList([d1])
d1.addErrback(self.errorHandler)
dl.addCallback(self.listCallback)
def errorHandler(self,result):
# Bad thingy!
pass
def pageCallback(self, result):
########### I added this, to hold the data:
self.data = result
return result
def listCallback(self, result):
print result
# Added for effect:
if reactor.running:
reactor.stop()
a = GrabPage('http://google.com')
########### Just call it without assigning to data
#data = a.start() # Not the HTML
a.start()
########### I added this:
if not reactor.running:
reactor.run()
########### Reference the data attribute from the class
data = a.data
print '------REACTOR STOPPED------'
print
########### First 100 characters of a.data:
print '------a.data[:100]------'
print data[:100]