aiohttp.client_exceptions.ClientConnectorError:无法连接到主机 stackoverflow.com:443 ssl:default [连接调用失败('151.101.193.69', 443)]

问题描述 投票:0回答:8

这是我的代码:

import asyncio
from aiohttp import ClientSession


async def main():
    url = "https://stackoverflow.com/"

    async with ClientSession() as session:
        async with session.get(url) as resp:
            print(resp.status)

asyncio.run(main())

如果我在我的计算机上运行它,一切正常,但如果我在 pythonanywhere 上运行它,我会收到此错误:

Traceback (most recent call last):
  File "/home/0dminnimda/.local/lib/python3.8/site-packages/aiohttp/connector.py", line 936, in _wrap_create_connection
    return await self._loop.create_connection(*args, **kwargs)  # type: ignore  # noqa
  File "/usr/lib/python3.8/asyncio/base_events.py", line 1017, in create_connection
    raise exceptions[0]
  File "/usr/lib/python3.8/asyncio/base_events.py", line 1002, in create_connection
    sock = await self._connect_sock(
  File "/usr/lib/python3.8/asyncio/base_events.py", line 916, in _connect_sock
    await self.sock_connect(sock, address)
  File "/usr/lib/python3.8/asyncio/selector_events.py", line 485, in sock_connect
    return await fut
  File "/usr/lib/python3.8/asyncio/selector_events.py", line 517, in _sock_connect_cb
    raise OSError(err, f'Connect call failed {address}')
ConnectionRefusedError: [Errno 111] Connect call failed ('151.101.193.69', 443)
The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "test_c.py", line 39, in <module>
    asyncio.run(main())
  File "/usr/lib/python3.8/asyncio/runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "/usr/lib/python3.8/asyncio/base_events.py", line 608, in run_until_complete
    return future.result()
  File "test_c.py", line 28, in main
    async with session.get(url, timeout=30) as resp:  # , headers=headers
  File "/home/0dminnimda/.local/lib/python3.8/site-packages/aiohttp/client.py", line 1012, in __aenter__
    self._resp = await self._coro
  File "/home/0dminnimda/.local/lib/python3.8/site-packages/aiohttp/client.py", line 480, in _request
    conn = await self._connector.connect(
  File "/home/0dminnimda/.local/lib/python3.8/site-packages/aiohttp/connector.py", line 523, in connect
    proto = await self._create_connection(req, traces, timeout)
  File "/home/0dminnimda/.local/lib/python3.8/site-packages/aiohttp/connector.py", line 858, in _create_connection
    _, proto = await self._create_direct_connection(
  File "/home/0dminnimda/.local/lib/python3.8/site-packages/aiohttp/connector.py", line 1004, in _create_direct_connection
    raise last_exc
  File "/home/0dminnimda/.local/lib/python3.8/site-packages/aiohttp/connector.py", line 980, in _create_direct_connection
    transp, proto = await self._wrap_create_connection(
  File "/home/0dminnimda/.local/lib/python3.8/site-packages/aiohttp/connector.py", line 943, in _wrap_create_connection
    raise client_error(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host stackoverflow.com:443 ssl:default [Connect call failed ('151.101.193.69', 443)]
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7f25a71d1a90>

aiohttp 托管:

Name: aiohttp
Version: 3.6.2
Summary: Async http client/server framework (asyncio)
Home-page: https://github.com/aio-libs/aiohttp
Author: Nikolay Kim
Author-email: [email protected]
License: Apache 2
Location: /home/0dminnimda/.local/lib/python3.8/site-packages
Requires: chardet, async-timeout, multidict, yarl, attrs
Required-by: 

我的电脑上的 aiohttp:

Name: aiohttp
Version: 3.6.2
Summary: Async http client/server framework (asyncio)
Home-page: https://github.com/aio-libs/aiohttp
Author: Nikolay Kim
Author-email: [email protected]
License: Apache 2
Location: c:\users\asus\appdata\roaming\python\python38\site-packages
Requires: async-timeout, attrs, chardet, yarl, multidict
Required-by: 

我很茫然,难道不是这样吗?我正在使用 python3.8 运行这两个文件。

我也尝试过其他网址,他们也有同样的问题

我需要添加更多细节吗?

python python-3.x python-asyncio aiohttp pythonanywhere
8个回答
26
投票

第一个解决方案

参考论坛的帮助,我在创建客户端时添加了

trust_env = True
,现在一切正常了。

说明: PythonAnywhere 上的免费帐户必须使用代理连接到公共互联网,但 aiohttp 默认情况下不会连接到可通过环境变量访问的代理。

aiohttp 文档的链接(查找名为“trust_env”的参数)

这是新代码:

import asyncio
from aiohttp import ClientSession


async def main():
    url = "https://stackoverflow.com/"

    async with ClientSession(trust_env=True) as session:
        async with session.get(url) as resp:
            print(resp.status)

asyncio.run(main())

如果第一个没有帮助您的解决方案

您尝试访问的域名必须在白名单中,否则您也可能会收到此错误。

在这种情况下,您需要在 pythonanywhere 论坛上发布新主题要求将域添加到白名单。
如果这是一个 api,那么您将需要提供该 api 文档的链接。


12
投票

如果您使用 Windows 操作系统 以及 python(3.8 或更高版本)和 aiohttp(3.7.4 或更早版本)
有时像

... Cannot connect to host <REQUESTED URL>:443 ssl:default [The parameter is incorrect]
这样的异常的解决方案是:

import sys

...

policy = asyncio.WindowsSelectorEventLoopPolicy()
asyncio.set_event_loop_policy(policy)

asyncio.run(main())

您可以检查您的Python版本和操作系统:

import sys

...

if (sys.platform.startswith('win')
        and sys.version_info[0] == 3
        and sys.version_info[1] >= 8):
    policy = asyncio.WindowsSelectorEventLoopPolicy()
    asyncio.set_event_loop_policy(policy)

asyncio.run(main())

这里,第4536期,所有内容都有更详细的描述。


4
投票

就我而言,问题是同时打开的连接数量非常大。为了解决这个问题,我将 limit 参数传递给 connector:

import aiohttp
conn = aiohttp.TCPConnector(limit_per_host=5)

async with aiohttp.ClientSession(connector=conn) as session:

3
投票

发出请求时将 ssl 设置为 False

import aiohttp
conn = aiohttp.TCPConnector()

async with aiohttp.ClientSession(connector=conn) as session:
    await session.get('https://example.com', ssl=False)

2
投票

来自文档:https://docs.aiohttp.org/en/stable/client_reference.html,协程异步请求的参数:

ssl
– SSL 验证模式。 None 用于默认 SSL 检查(使用 ssl.create_default_context()),False 用于跳过 SSL 证书验证,aiohttp.Fingerprint 用于指纹验证,ssl.SSLContext 用于自定义 SSL 证书验证。取代 verify_ssl、ssl_context 和指纹参数。

3.0版本新增功能。

import asyncio
from aiohttp import ClientSession


async def main():
    url = "https://stackoverflow.com/"

    async with ClientSession() as session:
        async with session.get(url, ssl=False) as resp:
            print(resp.status)

asyncio.run(main())

1
投票

我在 macOS 上遇到了同样的错误,这不是 aiohttp 问题。

尝试打开应用程序并查找 Install Certificates.command。运行。这解决了 macOS 上的问题。


0
投票

如果

ClientConnectorCertificateError
是由于
SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate')]
:

您有 3 个解决方案:

  1. [推荐方法]提供SSLContext来源
import ssl
import certifi

sslcontext = ssl.create_default_context(cafile=certifi.where())
async with session.get('https://example.com', ssl=sslcontext) as response:
    .....
  1. 安装证书来源

    1. 导航至
      cd /Applications/Python\ 3.11/
    2. 单击安装证书命令
  2. [不推荐] 禁用 SSL:

import aiohttp
connector=aiohttp.TCPConnector(ssl=False)

async with aiohttp.ClientSession(connector=connector) as session:
    await session.get('https://example.com')

-10
投票

我刚刚通过将所有

https
更改为
http
,在 5 分钟内解决了可能需要 3 小时的问题。如果可能的话,不要使用 https。我遇到了一个问题,另一个库(剧作家)无法使用选择器事件循环,我必须单独处理才能使用 aiohttp。更好的是,切换库,
httpx
是一个不错的选择。

© www.soinside.com 2019 - 2024. All rights reserved.