1

yield と task を使用して、4 つの 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も使用できません。では、呼び出し元関数ジェネレーターを作成せずにトルネードで関数から結果を返す方法は? 私はPython 2.7を使用しています

4

2 に答える 2

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 に答える