import asyncio, random, ssl
async def download(host):
ssl_context = ssl.create_default_context()
reader, writer = await asyncio.open_connection(host, 443, ssl=ssl_context)
request = f'HEAD / HTTP/1.1\r\nHost: {host}\r\n\r\n'
writer.write(request.encode('ascii'))
lines = list()
while True:
newdata = await reader.readline()
if newdata == b'\r\n':
break
else:
lines.append(newdata.decode('utf8').rstrip('\r\n'))
return lines[0]
async def main():
while True:
await asyncio.sleep(random.uniform(0.0, 0.5))
task.cancel()
try:
response = await task
print(response)
except asyncio.CancelledError:
print('request cancelled!')
except ssl.SSLError:
print('caught SSL error')
await asyncio.sleep(1)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
HTTP/1.1 200 OK
request cancelled!
HTTP/1.1 200 OK
HTTP/1.1 200 OK
<asyncio.sslproto.SSLProtocol object at 0x7fe7c00e5a20>: SSL handshake failed
Traceback (most recent call last):
File "/usr/lib/python3.6/asyncio/base_events.py", line 803, in _create_connection_transport
yield from waiter
File "/usr/lib/python3.6/asyncio/tasks.py", line 304, in _wakeup
future.result()
concurrent.futures._base.CancelledError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.6/asyncio/sslproto.py", line 577, in _on_handshake_complete
raise handshake_exc
File "/usr/lib/python3.6/asyncio/sslproto.py", line 638, in _process_write_backlog
ssldata = self._sslpipe.shutdown(self._finalize)
File "/usr/lib/python3.6/asyncio/sslproto.py", line 155, in shutdown
ssldata, appdata = self.feed_ssldata(b'')
File "/usr/lib/python3.6/asyncio/sslproto.py", line 219, in feed_ssldata
self._sslobj.unwrap()
File "/usr/lib/python3.6/ssl.py", line 692, in unwrap
return self._sslobj.shutdown()
ssl.SSLError: [SSL] shutdown while in init (_ssl.c:2299)