我必须发送大量HTTP请求,一旦所有HTTP请求都返回,程序就可以继续.听起来像是一场完美的比赛asyncio.有点天真,我把我的电话包裹requests在一个async函数中,然后把它们给了asyncio.这不起作用.
在线搜索后,我找到了两个解决方案:
asynciorun_in_executor为了更好地理解这一点,我写了一个小基准.服务器端是一个烧瓶程序,在回答请求之前等待0.1秒.
from flask import Flask
import time
app = Flask(__name__)
@app.route('/')
def hello_world():
time.sleep(0.1) // heavy calculations here :)
return 'Hello World!'
if __name__ == '__main__':
app.run()
Run Code Online (Sandbox Code Playgroud)
客户是我的基准
import requests
from time import perf_counter, sleep
# this is the baseline, sequential calls to requests.get
start = perf_counter()
for i in range(10):
r = requests.get("http://127.0.0.1:5000/")
stop = perf_counter()
print(f"synchronous took {stop-start} seconds") # 1.062 secs …Run Code Online (Sandbox Code Playgroud) 我在Python 3.6中为asyncio尝试了以下代码:示例1:
import asyncio
import time
async def hello():
print('hello')
await asyncio.sleep(1)
print('hello again')
tasks=[hello(),hello()]
loop=asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
Run Code Online (Sandbox Code Playgroud)
输出符合预期:
hello
hello
hello again
hello again
Run Code Online (Sandbox Code Playgroud)
然后我想将asyncio.sleep更改为另一个def:
async def sleep():
time.sleep(1)
async def hello():
print('hello')
await sleep()
print('hello again')
tasks=[hello(),hello()]
loop=asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
Run Code Online (Sandbox Code Playgroud)
输出:
hello
hello again
hello
hello again
Run Code Online (Sandbox Code Playgroud)
它似乎不是以异步模式运行,而是以正常同步模式运行.
问题是:为什么它不是以异步模式运行?如何将旧的同步模块更改为"异步"模块?