python - 如何编写可选择充当常规函数的 asyncio 协程?

标签 python python-3.x python-asyncio

我正在编写一个库,我希望最终用户能够有选择地使用它,就好像它的方法和函数不是协程一样。

例如,给定这个函数:

@asyncio.coroutine
def blah_getter():
    return (yield from http_client.get('http://blahblahblah'))

不想在自己的代码中使用任何异步功能的最终用户仍然需要导入 asyncio 并运行:

>>> response = asyncio.get_event_loop().run_until_complete(blah_getter())

如果我可以在 blah_getter 内部确定我是否作为协程被调用并做出相应 react ,那就太好了。

所以像这样:

@asyncio.coroutine
def blah_getter():
    if magically_determine_if_being_yielded_from():
        return (yield from http_client.get('http://blahblahblah'))
    else:
        el = asyncio.get_event_loop()
        return el.run_until_complete(http_client.get('http://blahblahblah'))

最佳答案

你需要两个函数——异步协程和同步正则函数:

@asyncio.coroutine
def async_gettter():
    return (yield from http_client.get('http://example.com'))

def sync_getter()
    return asyncio.get_event_loop().run_until_complete(async_getter())

magically_determine_if_being_yielded_from() 实际上是 event_loop.is_running() 但我强烈建议不要在同一个函数中混合使用同步和异步代码。

关于python - 如何编写可选择充当常规函数的 asyncio 协程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30155138/

相关文章:

python - 截断 SciPy 随机分布

python - 从 CSV 文件中读取特定行

python-3.x - 属性错误: module 'tensorflow.app' has no attribute 'flags'

python - 动态更改函数 __name__ 会抛出 AttributeError : 'method' object has no attribute '__name__'

python - 如何在 python 3 的版本之间进行更改

Python asyncio 不显示任何错误

python - BeautifulSoup 和 urllib 从网站查找数据

python - 当 asyncio.PriorityQueue 处于 maxsize 并且我 put() 新项目时,如何将项目从 asyncio.PriorityQueue 中推出?

python - 在范围内调用 asyncio Future

python - View 不存在错误