我正在尝试使用龙卷风期货实现this question的变体。排队有问题,因为我不想过去积累的数据。 IOW,我希望一个http请求处理程序能够阻塞等待原始启动后发生的另一个请求。

但是我想我缺少一步。

我的代码如下:

Events = dict()

class EventHandler(tornado.web.RequestHandler):
    @tornado.gen.coroutine
    def get(self, unit):
        # create  future to block on
        future = tornado.concurrent.Future()
        # store the future at a place the produce can find it
        Events[unit] = future
        # block waiting for the future's response
        result = yield future.result()
        # deregister the future
        Events.pop(unit, None)
        self.write(result)

    @tornado.gen.coroutine
    def post(self, unit):
        # fetch the corresponding future if there is one
        future = Events.get(unit, None)
        if future:
            # found one, set the result to pass body over
            future.set_result(self.request.body)
        else:
            print('noop')
        self.write(bytes())


发生的事情是我收到如下错误:

  File "./foo.py", line 44, in get
    result = yield future.result()
  File "/usr/lib/python3/dist-packages/tornado/concurrent.py", line 216, in result
    self._check_done()
  File "/usr/lib/python3/dist-packages/tornado/concurrent.py", line 294, in _check_done
    raise Exception("DummyFuture does not support blocking for results")


我没有正确使用Future吗?在配置它时,我还需要执行其他步骤吗?我是否应该制作一个实现该_check_done行为的子类?我是否认为龙卷风Future与其他系统的同义词马蹄莲promise是不正确的?除了仅使用未来/承诺,还有其他不同的方法吗?

最佳答案

您需要使用

result = yield future




result = yield future.result()


yield future.result()实际上等效于yield <whatever is returned by future.result()>。如果结果尚未准备好,则意味着result() API必须阻塞(意味着阻塞龙卷风事件循环),直到结果准备好为止,而tornado.concurrent.Future不支持该结果。您只能使用非阻塞yield future构造等待结果。

关于python - 被tornado.concurrent.Future异常混淆,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39297897/

10-12 22:22