异步aiohttp请求失败,但同步请求成功 [英] asynchronous aiohttp requests fails, but synchronous requests succeed

查看:425
本文介绍了异步aiohttp请求失败,但同步请求成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下代码,当我使用异步 aiohttp 无法连接到主机...:443 ssl:True $ c>。当我使用同步请求时,它会成功。

With the following code I get Cannot connect to host ...:443 ssl:True when I use the asynchronous aiohttp. When I use synchronous requests, it succeeds.

whitehouse.gov 链接失败,但 google.com 在异步和同步情况下均成功。

The whitehouse.gov links fail, but the google.com succeeds for both async and sync cases.

出了什么问题?这是FreeBSD8上的python 3.4.2,aiohttp 0.14.4,请求2.5.3

What is going wrong? This is with python 3.4.2 on FreeBSD8, aiohttp 0.14.4, requests 2.5.3

import asyncio
import aiohttp
import requests

urls = [
    'http://www.whitehouse.gov/cea/', 
    'http://www.whitehouse.gov/omb', 
    'http://www.google.com']


def test_sync():
    for url in urls:
        r = requests.get(url)
        print(r.status_code)


def test_async():
    for url in urls:
        try:
            r = yield from aiohttp.request('get', url)
        except aiohttp.errors.ClientOSError as e:
            print('bad eternal link %s: %s' % (url, e))
        else:
            print(r.status)


if __name__ == '__main__':
    print('async')
    asyncio.get_event_loop().run_until_complete(test_async())
    print('sync')
    test_sync()

此输出为:

async
bad eternal link http://www.whitehouse.gov/cea: Cannot connect to host www.whitehouse.gov:443 ssl:True
bad eternal link http://www.whitehouse.gov/omb: Cannot connect to host www.whitehouse.gov:443 ssl:True
200
sync
200
200
200


推荐答案

我怀疑证书验证链在您的计算机上已损坏。
在Ubuntu上一切正常,如@dano所述。

I suspect certificate validation chain is broken on your machine. On Ubuntu everything is working, as @dano mentioned.

无论如何,您可以通过创建自定义 Connector 实例:

Anyway, you may disable ssl validation by creating custom Connector instance:

import asyncio
import aiohttp

urls = [
    'http://www.whitehouse.gov/cea/',
    'http://www.whitehouse.gov/omb',
    'http://www.google.com']


def test_async():
    connector = aiohttp.TCPConnector(verify_ssl=False)
    for url in urls:
        try:
            r = yield from aiohttp.request('get', url, connector=connector)
        except aiohttp.errors.ClientOSError as e:
            print('bad eternal link %s: %s' % (url, e))
        else:
            print(r.status)


if __name__ == '__main__':
    print('async')
    asyncio.get_event_loop().run_until_complete(test_async())

BTW,请求库附带了自己的证书捆绑包。也许我们需要对aiohttp做同样的事情?

BTW, requests library is shipped with own certificate bundle. Maybe we need to do the same for aiohttp?

UPD。另请参见 https://github.com/aio-libs/aiohttp/issues/341

这篇关于异步aiohttp请求失败,但同步请求成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆