0

I'm trying to send an https requests using socket in python, however I'm facing this error even when I tried to use the snippet in the documentations to test if the issue is in my code or maybe somewhere else. here is the snippet I took from the documentations :

import socket
import ssl

hostname = 'www.python.org'
context = ssl.create_default_context()

with socket.create_connection((hostname, 443)) as sock:
    with context.wrap_socket(sock, server_hostname=hostname) as ssock:
        print(ssock.version())

and here is the error I'm getting :

Traceback (most recent call last):
File "file.py", line 7, in <module>
with socket.create_connection((hostname, 443)) as sock:
AttributeError: __exit__

am I missing something here ? , I need to use sockets not requests or any other library

no one
  • 25
  • 7
  • The code works with python3.6.2 I see you tagged this python2.7 can you please provide a link to the documentation you are referencing? – James Powis Apr 15 '20 at 03:01
  • This has your answer https://stackoverflow.com/questions/49472282/python-socket-attributeerror-exit with socket.create_connection(...) was added in python3.2 – James Powis Apr 15 '20 at 03:08

1 Answers1

1

For python 2.7 you need to do the following:

import socket
import ssl

hostname = 'www.python.org'
context = ssl.create_default_context()

sock = socket.create_connection((hostname, 443))
ssock = context.wrap_socket(sock, server_hostname=hostname)
print(ssock.version())
James Powis
  • 609
  • 4
  • 16