【问题标题】:Twisted: Wait for a deferred to 'finish'Twisted:等待延迟“完成”
【发布时间】:2013-10-08 19:48:47
【问题描述】:

我怎样才能将 deferred '扔'到反应堆中,以便在路上的某个地方处理它?

情况

我有 2 个程序在 localhost 上运行。

  1. 一个扭曲的 jsonrpc 服务 (localhost:30301)
  2. 扭曲的网络服务 (localhost:4000)

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

我似乎不知道如何返回延迟的 jsonrpc 调用的值。当我使用浏览器访问 Web 服务时,我收到 HTML 500 错误代码(未返回任何字节)和值:。

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

在询问之前已经环顾了几个小时并尝试了很多不同的变化。

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

【问题讨论】:

    标签: python twisted deferred reactor


    【解决方案1】:

    您在这里遇到的问题是网络的IResource 是一个非常古老的界面,甚至早于Deferred

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

    解决这个问题的稍微迂回的方式是read the chapter of the Twisted documentation,它专门针对twisted.web 中的异步响应。

    【讨论】:

    • 克莱恩看起来不错!感谢您的描述性回答。
    猜你喜欢
    • 2012-05-27
    • 1970-01-01
    • 1970-01-01
    • 2013-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多