0
import time
import urllib.request
import asyncio
import aiohttp
URL = 'https://api.github.com/events'
MAX_CLIENTS = 10
def fetch_sync(pid):
print('Fetch sync process {} started'.format(pid))
start = time.time()
response = urllib.request.urlopen(URL)
datetime = response.getheader('Date')
print('Process {}: {}, took: {:.2f} seconds'.format(
pid, datetime, time.time() - start))
return datetime
async def fetch_async(pid):
print('Fetch async process {} started'.format(pid))
start = time.time()
response = await aiohttp.request('GET', URL)
datetime = response.headers.get('Date')
print('Process {}: {}, took: {:.2f} seconds'.format(
pid, datetime, time.time() - start))
response.close()
return datetime
def synchronous():
start = time.time()
for i in range(1, MAX_CLIENTS + 1):
fetch_sync(i)
print("Process took: {:.2f} seconds".format(time.time() - start))
async def asynchronous():
start = time.time()
tasks = [asyncio.ensure_future(
fetch_async(i)) for i in range(1, MAX_CLIENTS + 1)]
await asyncio.wait(tasks)
print("Process took: {:.2f} seconds".format(time.time() - start))
print('Synchronous:')
synchronous()
print('Asynchronous:')
ioloop = asyncio.get_event_loop()
ioloop.run_until_complete(asynchronous())
ioloop.close()
I’m studying the Python asyncIO module and came across this code on Github(https://github.com/yeraydiazdiaz/asyncio-ftwpd) but the same is generating this error:
Traceback (most recent call last):
File "test_one.py", line 198, in fetch_async
response = await aiohttp.request('GET', URL)
TypeError: object _SessionRequestContextManager can't be used in 'await' expression
I don’t know much about the module yet, someone could tell me why this error is occurring and how I can do it in the right way. Thank you in advance.
Would you know how to define async with aiohttp.Clientsession() as Session, or an asynchronous context manager, what is its use in code ???
– ThiagoO