我有以下问题,我的api请求代码确实是非确定性的。我使用asyncio
来发出异步请求,因为我想发送多个请求并且频率变化很大(这就是我发送30个相同请求的原因)。有时我的代码执行速度非常快,大约0.5秒,但有时它会在发送一半请求之后卡住。谁能看到一些可能产生以下错误的代码错误?或者这样的事情是由服务器响应的一些延迟引起的?
import asyncio
from aiohttp import ClientSession
async def fetch(url, session):
async with session.get(url) as response:
data = await response.json()
print(data)
return await response.read()
async def run(r):
url = "https://www.bitstamp.net/api/ticker/"
tasks = []
async with ClientSession() as session:
for i in range(r):
task = asyncio.ensure_future(fetch(url.format(i), session))
tasks.append(task)
responses = asyncio.gather(*tasks)
await responses
t1 = time.time()
number = 30
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(run(number))
loop.run_until_complete(future)
t2= time.time()
print(t2-t1)