【问题标题】:Can't Call result on futures tornado , always result object不能在期货龙卷风上调用结果,总是结果对象
【发布时间】:2017-11-13 22:21:49
【问题描述】:
from somefolder import somelibrary

@gen.coroutine
def detailproduct(url):
    datafromlib=yield somelibrary(url)
    raise gen.Return(datafromlib)

期望: 查看没有请求处理程序的结果。 结果不像

{"data":<tornado.concurrent.future>}

我试试这个链接: "Can't call result() on futures in tornado" 但不行。

谁来帮帮我!交易

【问题讨论】:

    标签: python python-2.7 server tornado


    【解决方案1】:

    在使用gen.coroutine 时,您必须牢记两条规则:

    1. gen.coroutine 修饰的函数会自动返回一个 Future。
    2. 如果一个函数/协程正在调用另一个用gen.coroutine 修饰的协程,它也必须用gen.coroutine 修饰,并且必须使用yield 关键字才能得到它的结果。

    detailproductgen.coroutine 装饰——这意味着它总是会返回包裹在 Future 中的 datafromlib


    如何解决

    根据规则 2,您必须使用 gen.coroutine 装饰调用方,并使用 yield 关键字来获取 Future 的结果。

    @gen.coroutine
    def my_func():
        data = yield detailproduct(url) 
        # do something with the data ...
    

    您可以在 Future 上设置一个回调函数,当它被解析时将被调用。但这会使代码变得混乱。

    def my_fun():
        data_future = detailproduct(url)
        data_future.add_done_callback(my_callback)
    
    def my_callback(future):
        data = future.result()
        # do something with the data ...
    

    【讨论】:

      猜你喜欢
      • 2015-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-13
      • 1970-01-01
      相关资源
      最近更新 更多