python – 扭曲:等待推迟到’完成’

我怎样才能“推迟”进入反应堆,以便在未来的某个地方处理?

情况

我在localhost上运行了2个程序.

>扭曲的jsonrpc服务(localhost:30301)
>扭曲的web服务(localhost:4000)

当有人连接到Web服务时,它需要向jsonrpc服务发送查询,等待它返回结果,然后在用户的Web浏览器中显示结果(返回jsonrpc调用的值).

我似乎无法弄清楚如何返回延迟jsonrpc调用的值.当我使用浏览器访问webservice时,我得到一个HTML 500错误代码(没有返回任何字节)和Value:<推迟到0x3577b48>.

它返回延迟对象,而不是回调的实际值.

一直在环顾四个小时,并在询问前尝试了很多不同的变化.

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()

解决方法:

你在这里遇到的问题是web的IResource是一个非常古老的界面,甚至比Deferred更早.

问题的快速解决方案是使用Klein,它为twisted.web提供了一个非常方便的高级包装,用于编写Web应用程序,除此之外,还为整个API中的Deferred添加了大量处理.

稍微更迂回的解决方法是read the chapter of the Twisted documentation,具体是关于twisted.web中的异步响应.

上一篇:javascript – 从JS中被拒绝的承诺中恢复


下一篇:推迟PHP代码有什么办法吗?