[英]Twisted: Wait for a deferred to 'finish'
How can I 'throw' deferred's into the reactor so it gets handled somewhere down the road? 我怎样才能“推迟”进入反应堆,以便在未来的某个地方处理?
Situation 情况
I have 2 programs running on localhost. 我在localhost上运行了2个程序。
When someone connects to the webservice, It needs to send a query to the jsonrpc service, wait for it to come back with a result, then display the result in the web browser of the user (returning the value of the jsonrpc call). 当有人连接到Web服务时,它需要向jsonrpc服务发送查询,等待它返回结果,然后在用户的Web浏览器中显示结果(返回jsonrpc调用的值)。
I can't seem to figure out how to return the value of the deferred jsonrpc call. 我似乎无法弄清楚如何返回延迟jsonrpc调用的值。 When I visit the webservice with my browser I get a HTML 500 error code (did not return any byte) and Value: < Deferred at 0x3577b48 >.
当我使用浏览器访问web服务时,我得到一个HTML 500错误代码(没有返回任何字节)和值:<延迟到0x3577b48>。
It returns the deferred object and not the actual value of the callback. 它返回延迟对象,而不是回调的实际值。
Been looking around for a couple of hours and tried a lot of different variations before asking. 一直在环顾四个小时,并在询问前尝试了很多不同的变化。
from txjsonrpc.web.jsonrpc import Proxy
from twisted.web import resource
from twisted.web.server import Site
from twisted.internet import reactor
class Rpc():
def __init__(self, child):
self._proxy = Proxy('http://127.0.0.1:30301/%s' % child)
def execute(self, function):
return self._proxy.callRemote(function)
class Server(resource.Resource):
isLeaf = True
def render_GET(self, request):
rpc = Rpc('test').execute('test')
def test(result):
return '<h1>%s</h1>' % result
rpc.addCallback(test)
return rpc
site = Site(Server())
reactor.listenTCP(4000, site)
print 'Running'
reactor.run()
The problem you're having here is that web's IResource
is a very old interface, predating even Deferred
. 你在这里遇到的问题是web的
IResource
是一个非常古老的界面,甚至比Deferred
。
The quick solution to your problem is to use Klein , which provides a nice convenient high-level wrapper around twisted.web for writing web applications, among other things, adding lots of handling for Deferred
s throughout the API. 解决问题的快速方法是使用Klein ,它为twisted.web提供了一个非常方便的高级包装器,用于编写Web应用程序,除此之外,还为整个API中的
Deferred
添加了大量处理。
The slightly more roundabout way to address it is to read the chapter of the Twisted documentation that is specifically about asynchronous responses in twisted.web. 解决它的稍微迂回的方法是阅读Twisted文档的章节,该章节专门讨论twisted.web中的异步响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.