async,await实现异步

来源:14-2 fastapi 框架的使用

慕标1049315

2021-04-25

老师,我把课程代码稍微补充了下。想模拟异步网站请求。但从耗时来看,执行是同步的。我猜可能因为for循环是同步的。但不知怎么修改代码,或者说,要用async,await实现这样的需求,该怎么写代码呢?图片描述

写回答

2回答

bobby

2021-04-27

await asyncio.sleep(3)

你的sleep要换成这个,课程中专门强调过的,不能使用阻塞的sleep

1
1
慕标1049315
非常感谢!
2021-05-09
共1条回复

bobby

2021-04-27

你把完整的代码贴一下 我运行一下试试把

0
1
慕标1049315
完整代码如下: import asyncio import time async def downloader(url): # 模拟下载 time.sleep(3) res = "download from{}".format(url) return res async def handle(url_list): res = '' for url in url_list: html = await downloader(url) res += html return res if __name__ == "__main__": urls = ["http://www.baidu.com", "http://www.sina.com"] coro = handle(urls) start_time = time.time() try: coro.send(None) except StopIteration as e: print(e.value) print("耗时:", time.time()-start_time)
2021-04-27
共1条回复

Python3高级核心技术97讲,高级进阶的必学课程

socket编程/多线程/多进程/线程池/asyncio并发编程/协程和异步IO

2121 学习 · 551 问题

查看课程