【发布时间】:2019-06-13 20:58:38
【问题描述】:
先开发一个简单的实现是正常的。因此,例如,我们可能从一个非并发程序开始,然后添加并发。我希望能够顺畅地来回切换。
例如单线程(伪代码):
results=[]
for url in urls:
# This then calls other functions that call yet others
# in a call hierarchy, down to a requests.request() call.
get_result_and_store_in_database(url)
异步(伪代码):
# The following calls other functions that call yet others
# in a call hierarchy, down to an asyncio ClientSession().get() call.
# It runs HTTP requests and store the results in a database.
# The multiple URLs are processed concurrently.
asyncio.run(get_results_in_parallel_and_store_in_db(urls))
使用 Python async/await,通常你用asyncio.run() 包装运行(与你在普通程序中使用的循环相比);然后在调用层次结构的底部,使用类似aiohttp.ClientSession().get(url) 的IO 操作(与普通的requests.request() 相比。)
但是,在异步版本中,这两者之间的调用层次结构中的所有函数都必须写为async/await。因此,我需要编写两个基本相同的调用层次结构的副本,主要区别在于它们是否具有 async/await 关键字。
那是很多代码重复。
如何制作可切换的非并发/异步程序?
【问题讨论】:
-
同步/异步代码具有根本不同的运行时期望。假设性地回答这个问题有点太宽泛了;一个具体的例子可能更容易回答。
-
deceze:下面@sraw 的回答显示了一个例子,或者看我上面的伪代码
标签: python python-3.x async-await python-asyncio