【问题标题】:Tornado coroutine yield from another coroutine incrementallyTornado 协程逐渐从另一个协程中产生
【发布时间】:2018-11-21 16:15:20
【问题描述】:

我想重构我的 Tornado 应用程序的一部分,所以我创建了一个特殊的函数来返回电话号码:

@gen.coroutine
def get_phones(self, listname):
    phones = []
    logging.info("fetching phones")
    cursor = self._mongo.contacts.aggregate(self.get_query(
        subscription_filter={
            "$ne": [{"$ifNull": ["$$subscription.events.{listname}", None]}, None]
        },
        handler_filter={
            "handler.meta.is_active": True,
            "handler.meta.type": "phone"
        }
    ))
    try:
        while (yield cursor.fetch_next):
            contact = cursor.next_object()
            logging.info(contact)
            try:
                phones += [handler['subject'] for handler in contact['handlers']]
                if len(phones) > 50:
                    yield phones
                    phones = []
            except Exception:
                self._logger.warning("Could not get phone no")
    except Exception:
        phones = []
        logging.warning("Could not fetch contacts")

    if len(phones) > 0:
        yield phones

我想要实现的是从我的数据库中异步获取最多 50 个联系人的批次并将它们返回给调用协程。

这是我的调用协程:

@gen.coroutine
def on_heartbeat_status_update(self, status):
    phonegen = self.get_phones("ews:admin")
    logging.info(phonegen)
    while True:
        phones = yield phonegen
        logging.info(phones)
        if phones is None:
            break
        logging.info(len(phones))

它不工作。 “电话”总是无。有人可以建议实现这一目标的正确方法吗?谢谢!

【问题讨论】:

    标签: tornado coroutine


    【解决方案1】:

    您必须使用 Python 3.6 原生协程才能使其正常工作。这是第一个在同一函数中同时支持yield 和await 的Python 版本。没有这个,系统就无法区分使用yield 作为协程和生成结果作为生成器。

    将@gen.coroutine def 替换为async def 并在get_phones 中使用await cursor.fetch_next 和yield phones。然后你可以在on_heartbeat_status_update 中使用async for phones in self.get_phones(...)。

    【讨论】:

    • 谢谢本!你的建议成功了。不过,我还需要弄清楚一件事。如果 get_phones() 函数产生很多东西怎么办?如何确保在调用函数中安排在 ioloop 上的其他内容有机会运行?
    • 这样做:self.get_phones("ews:admin") 中的电话列表异步:self.send_sms(sms,phonelist) await tornado.gen.sleep(0) 似乎不起作用。如果我在 get_phones 函数中让一段时间为 True,那么 IOloop 上的其他任何东西都没有机会运行。
    • await sleep(0) 应该允许其他东西运行。我不确定这里会发生什么。
    • 根据我的测试,await sleep(0.01) 确实允许其他事情发生,但根据我的观察,仅仅执行 await sleep(0) 并没有。可能是我做错的其他事情。我会继续挖掘。
    猜你喜欢
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 2017-06-04
    • 2017-03-26
    • 1970-01-01
    • 2015-07-02
    相关资源
    最近更新 更多