对于在Windows上的Python 3.4中使用asyncio和aiohttp的https请求,我需要使用2个事件循环。一个ProactorEventLoop,用于运行Shell命令,以及用于HTTPS请求的默认事件循环。不幸的是,ProactorEventLoop不适用于HTTPS命令。
下面的代码显示了当我使用新创建的默认事件循环并尝试在Windows上最终将其关闭时发生的情况。如果我loop.close
在末尾调用,则在末尾出现异常,如下所示:
> Traceback (most recent call last):
> File "C:\BuildUtilities\p3.4env0\lib\site-packages\aiohttp\connector.py", line 56, in __del__
> self.close()
> File "C:\BuildUtilities\p3.4env0\lib\site-packages\aiohttp\connector.py", line 97, in close
> transport.close()
> File "C:\Python34\Lib\asyncio\selector_events.py", line 375, in close
> self._loop.remove_reader(self._sock_fd)
> File "C:\Python34\Lib\asyncio\selector_events.py", line 155, in remove_reader
> key = self._selector.get_key(fd)
> AttributeError: 'NoneType' object has no attribute 'get_key'
注释掉它会删除该异常,我不知道为什么。唯一的
import asyncio
import aiohttp
@asyncio.coroutine
def get_body(url):
response = yield from aiohttp.request('GET', url)
return (yield from response.read_and_close())
#loop = asyncio.ProactorEventLoop()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
f = asyncio.async( get_body('https://www.google.com') )
try:
loop.run_until_complete(f)
except Exception as e:
print(e)
if f.result():
print(f.result())
loop.close()
谢谢,greenaj
更新:看起来该问题已在github版本(0.7.2)中修复。它不会产生错误。正如@ danj.py所说,它是通过“摆脱__del__
连接器” commit来解决的。
它不是ProactorEventLoop或Windows特定的。我可以使用默认事件循环在Ubuntu上重现该错误:
#!/usr/bin/env python3
import asyncio
import aiohttp # $ pip install aiohttp
@asyncio.coroutine
def get_body(url):
response = yield from aiohttp.request('GET', url)
return (yield from response.read_and_close())
loop = asyncio.get_event_loop()
body = loop.run_until_complete(get_body('https://stackoverflow.com/q/23283502'))
print(len(body), type(body), body[:200])
loop.close()
这可能是aiohttp中的错误,因为用法似乎正确。
如果发出的请求没有以下内容,则没有错误aiohttp
:
#!/usr/bin/env python3
import asyncio
from contextlib import closing
from urllib.parse import urlsplit
@asyncio.coroutine
def get_body(url):
# parse url
url = urlsplit(url)
path = '/' * (not url.path) + url.path + '?' * bool(url.query) + url.query
# open connection
reader, writer = yield from asyncio.open_connection(
host=url.hostname,
port=url.port or (443 if url.scheme == 'https' else 80),
ssl=(url.scheme == 'https'))
with closing(writer):
# send request
writer.write(b'GET ' + path.encode('ascii') + b' HTTP/1.1\r\n'
b'Host: ' + url.netloc.encode('ascii') + b'\r\n'
b'Connection: close\r\n\r\n')
# read headers
while True:
line = yield from reader.readline()
line = line.rstrip(b'\n\r')
print(line.decode('latin-1'))
if not line:
break
# read body
body = yield from reader.read()
return body
loop = asyncio.get_event_loop()
body = loop.run_until_complete(get_body('https://stackoverflow.com/q/23283502'))
print(len(body), type(body), body[:200])
loop.close()
注意:这些示例并不完全等效,例如,后者不遵循重定向。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句