D
D
den4ik_ept12018-05-24 21:08:42
Python
den4ik_ept1, 2018-05-24 21:08:42

Why await aiohttp.request doesn't work python 3?

Decided to learn asynchronous programming
Faced this error more than once, I can't figure out what's wrong

File "C:/Users/user/PycharmProjects/untitled/main.py", line 32, in fetch_async
    response = await aiohttp.request('GET', URL) 
TypeError: object _SessionRequestContextManager can't be used in 'await' expression

Program source code
import time
import asyncio
import aiohttp

URL = 'https://api.github.com/events'
MAX_CLIENTS = 1
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


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))

ioloop = asyncio.get_event_loop()
ioloop.run_until_complete(asynchronous())
ioloop.close()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2018-05-24
@den4ik_ept1

Tested with Python 3.6.3 and aiohttp 2.3.6 - works.

N
Nick V, 2018-05-24
@half-life

den4ik_ept1 Read the doc dude.
And yet, if there are any misunderstandings with third-party libraries, then indicate the exact version that you are using.
Here is the working code. Compare, understand.

Python 3.6.5 (default, Mar 29 2018, 03:28:50)
[GCC 5.4.0 20160609] on linux

import asyncio
import logging
import sys
import time

import aiohttp

logger = logging.getLogger('aiohttp_test')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)

URL = 'https://api.github.com/events'
MAX_CLIENTS = 2


async def fetch_async(session, pid):
    logger.info(f'Fetch async process {pid} started')
    start = time.time()
    async with session.get(URL) as response:
        datetime = response.headers.get('Date')
    logger.info(f'Process {pid}: {datetime}, took: {time.time() - start} seconds')
    return datetime


async def asynchronous():
    start = time.time()
    async with aiohttp.ClientSession() as session:
        tasks = [asyncio.ensure_future(
            fetch_async(session, pid)) for pid in range(1, MAX_CLIENTS + 1)]
        await asyncio.gather(*tasks)
    logger.info(f'Process took: {time.time() - start} seconds')


if __name__ == '__main__':
    io_loop = asyncio.get_event_loop()
    try:
        logger.info('Script has been started')
        io_loop.run_until_complete(asynchronous())
    except Exception as e:
        logger.exception(e)
    finally:
        logger.info('Script has been finished')
        io_loop.close()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question