Python:如何使用龙卷风从生成器函数返回?

时间:2013-05-27 15:34:31

标签: python generator tornado yield

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

@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。那么,如何在没有调用函数生成器的情况下从龙卷风函数返回结果呢? 我正在使用Python 2.7

2 个答案:

答案 0 :(得分:5)

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

你可以在没有任何值的情况下调用return来导致StopIteration异常并结束生成器,但是返回一个值在语义上没有意义。

如果你想有时候返回一个生成器,有时会返回一个值,用另一个返回一个生成器(通过调用这个函数创建)或替代值来包装你的函数,虽然我不是这样的从设计的角度来看,这通常是个坏主意。

答案 1 :(得分: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)

引擎是一个较旧的界面;更多关于这一点,你可以看到龙卷风3.0文件。