Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aiohttp error "Connect call failed" for multiple async requests to localhost

I am new to aiohttp and was just testing some of it's functionality. So I created a simple client and server script to see how many requests the async code could handle but I'm running into an error.

The server script is as follows:

from aiohttp import web

# Initialize counter
counter = 1

# View index function
async def index(request):
    # Increments counter
    global counter
    counter += 1

    # Return data
    data = {'test': counter}
    return web.json_response(data)

# Creating application
app = web.Application()

# Registering route
app.router.add_get('/', index)

# Starting server
web.run_app(app, host='127.0.0.1', port=8080)

The client script is as follows:

import asyncio, time, aiohttp
from aiohttp import ClientSession

# Initialize counter
COUNT = 0
requests = 2

async def fetch(url, session):
    async with session.get(url) as response:
        return await response.read()

async def run(r):
    url = "http://localhost:8080/"
    tasks = []
    global COUNT

    # Fetch all responses within one Client session,
    # keep connection alive for all requests.
    async with ClientSession(connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
        for i in range(r):
            task = asyncio.ensure_future(fetch(url, session))
            tasks.append(task)
            COUNT += 1

        responses = await asyncio.gather(*tasks)
        # you now have all response bodies in this variable
        print(responses)

# Start timing the process
start = time.time()

loop = asyncio.get_event_loop()
future = asyncio.ensure_future(run(requests))
loop.run_until_complete(future)

# Process complete output
print("The final counter value is: " + str(COUNT))
print("The total time elapsed is: " + str(time.time() - start))

The output error message is as follows when I try to run the client script:

Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\lib\site-packages\aiohttp\connector.py", line 796, in _wrap_create_connection
    return (yield from self._loop.create_connection(*args, **kwargs))
  File "C:\ProgramData\Anaconda3\lib\asyncio\base_events.py", line 776, in create_connection
    raise exceptions[0]
  File "C:\ProgramData\Anaconda3\lib\asyncio\base_events.py", line 763, in create_connection
    yield from self.sock_connect(sock, address)
  File "C:\ProgramData\Anaconda3\lib\asyncio\selector_events.py", line 451, in sock_connect
    return (yield from fut)
  File "C:\ProgramData\Anaconda3\lib\asyncio\selector_events.py", line 481, in _sock_connect_cb
    raise OSError(err, 'Connect call failed %s' % (address,))
ConnectionRefusedError: [Errno 10061] Connect call failed ('::1', 8080)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "async.py", line 34, in <module>
    loop.run_until_complete(future)
  File "C:\ProgramData\Anaconda3\lib\asyncio\base_events.py", line 466, in run_until_complete
    return future.result()
  File "async.py", line 25, in run
    responses = await asyncio.gather(*tasks)
  File "async.py", line 9, in fetch
    async with session.get(url) as response:
  File "C:\ProgramData\Anaconda3\lib\site-packages\aiohttp\client.py", line 690, in __aenter__
    self._resp = yield from self._coro
  File "C:\ProgramData\Anaconda3\lib\site-packages\aiohttp\client.py", line 267, in _request
    conn = yield from self._connector.connect(req)
  File "C:\ProgramData\Anaconda3\lib\site-packages\aiohttp\connector.py", line 402, in connect
    proto = yield from self._create_connection(req)
  File "C:\ProgramData\Anaconda3\lib\site-packages\aiohttp\connector.py", line 748, in _create_connection
    _, proto = yield from self._create_direct_connection(req)
  File "C:\ProgramData\Anaconda3\lib\site-packages\aiohttp\connector.py", line 859, in _create_direct_connection
    raise last_exc
  File "C:\ProgramData\Anaconda3\lib\site-packages\aiohttp\connector.py", line 831, in _create_direct_connection
    req=req, client_error=client_error)
  File "C:\ProgramData\Anaconda3\lib\site-packages\aiohttp\connector.py", line 803, in _wrap_create_connection
    raise client_error(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host localhost:8080 ssl:False [Connect call failed ('::1', 8080)]

I am running:

  • Python 3.6.1
  • Anaconda 4.4.0 (64-bit)
  • Windows 10
  • aiohttp 2.3.6

The client script works if I am only making 1 request which isn't very useful or if I make requests to example.com but not to localhost. What am I missing here?

like image 264
Brian Avatar asked Dec 29 '17 14:12

Brian


1 Answers

Replace localhost by 127.0.0.1 in client code.

Looks like localhost is resolved to ::1 but server is hosted on 127.0.0.1 only.

like image 145
Andrew Svetlov Avatar answered Sep 29 '22 17:09

Andrew Svetlov