1

我使用 yield 和 task 来异步获取四个 json:

@gen.engine
def get_user_data(self, sn, snid, fast_withdrawals):
    end_timestamp = time.time()
    start_timestamp = end_timestamp - CONFIG.LOYALITY_LEVELS.PERIOD

    active_apps_response, total_payments_response, payments_for_period_response, withdrawals_response = yield [
        gen.Task(self.http_client.fetch, self.__get_active_apps_url(sn, snid)), gen.Task(self.http_client.fetch, self.__get_total_payments_url(sn, snid)),
        gen.Task(self.http_client.fetch, self.__get_payments_sum_for_period_url(sn, snid, start_timestamp, end_timestamp)),
        gen.Task(self.http_client.fetch, self.__get_total_withdrawals_url(sn, snid, fast_withdrawals))
    ]

    active_apps = self.__active_apps_handler(active_apps_response)
    total_payments = self.__get_total_payments_handler(total_payments_response)
    payments_for_period = self.__payments_sum_for_period_handler(payments_for_period_response)
    withdrawals = self.__get_total_withdrawals_handler(withdrawals_response)

    yield gen.Return(active_apps, total_payments, payments_for_period, withdrawals)

但是,如果我使用 yield 而不是 return upper 函数也成为生成器,我也不能在其中使用 return 。那么,如何在不制作调用函数生成器的情况下从龙卷风中的函数返回结果?我正在使用 Python 2.7

4

2 回答 2

5

您不能同时返回值和产生值。当您产生值时,该函数返回一个生成器 - 因此它已经返回一个值并且不能返回更多。这样做根本没有意义。

您可以return在没有任何值的情况下调用以引发StopIteration异常并结束生成器,但从生成器中返回值在语义上没有意义。

如果你想有时返回一个生成器,有时返回一个值,用另一个返回生成器(通过调用此函数创建)或替代值的函数包装你的函数,尽管我不认为这样的事情通常是一件坏事从设计角度的想法。

于 2013-05-27T15:35:18.047 回答
0

也许你可以这样写:

@gen.coroutine
def get_user_data(self, sn, snid, fast_withdrawals):
    end_timestamp = time.time()
    start_timestamp = end_timestamp - CONFIG.LOYALITY_LEVELS.PERIOD

    active_apps_response, total_payments_response, payments_for_period_response, withdrawals_response = yield [
    self.http_client.fetch(self.__get_active_apps_url(sn, snid)),
    self.http_client.fetch(self.__get_total_payments_url(sn, snid)),
    self.http_client.fetch(self.__get_payments_sum_for_period_url(sn, snid, start_timestamp, end_timestamp)),
    self.http_client.fetch(self.__get_total_withdrawals_url(sn, snid, fast_withdrawals))
]

active_apps = self.__active_apps_handler(active_apps_response)
total_payments = self.__get_total_payments_handler(total_payments_response)
payments_for_period = self.__payments_sum_for_period_handler(payments_for_period_response)
withdrawals = self.__get_total_withdrawals_handler(withdrawals_response)

raise gen.Return(active_apps, total_payments, payments_for_period, withdrawals)

引擎是较旧的界面;有关此的更多信息,您可以查看 tornado 3.0 文档。

于 2013-05-28T22:15:42.493 回答