针对localhost的多个异步请求,Aiohttp错误“连接呼叫失败”

时间:2017-12-29 14:13:37

标签: python-3.x aiohttp

我是aiohttp的新手,只是测试了它的一些功能。所以我创建了一个简单的客户端和服务器脚本来查看异步代码可以处理的请求数,但是我遇到了错误。

服务器脚本如下:

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)

客户端脚本如下:

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

当我尝试运行客户端脚本时,输出错误消息如下:

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

我正在跑步:

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

如果我只发出1个不太有用的请求,或者我向example.com发出请求但不向localhost发出请求,则客户端脚本可以正常工作。我在这里缺少什么?

1 个答案:

答案 0 :(得分:3)

在客户端代码中将localhost替换为127.0.0.1

localhost似乎已解析为::1,但服务器仅托管在127.0.0.1上。