Python httplib.HTTPSConnection() Examples

The following are code examples for showing how to use httplib.HTTPSConnection(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_httplib.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_host_port(self):
        # Check invalid host_port

        for hp in ("www.python.org:abc", "user:[email protected]"):
            self.assertRaises(httplib.InvalidURL, httplib.HTTPSConnection, hp)

        for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
                          "fe80::207:e9ff:fe9b", 8000),
                         ("www.python.org:443", "www.python.org", 443),
                         ("www.python.org:", "www.python.org", 443),
                         ("www.python.org", "www.python.org", 443),
                         ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
                         ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
                             443)):
            c = httplib.HTTPSConnection(hp)
            self.assertEqual(h, c.host)
            self.assertEqual(p, c.port) 
Example 2
Project: L.E.S.M.A   Author: NatanaelAntonioli   File: L.E.S.M.A. - Fabrica de Noobs Speedtest.py    Apache License 2.0 6 votes vote down vote up
def validate_optional_args(args):
	"""Check if an argument was provided that depends on a module that may
	not be part of the Python standard library.

	If such an argument is supplied, and the module does not exist, exit
	with an error stating which module is missing.
	"""
	optional_args = {
		'json': ('json/simplejson python module', json),
		'secure': ('SSL support', HTTPSConnection),
	}

	for arg, info in optional_args.items():
		if getattr(args, arg, False) and info[1] is None:
			raise SystemExit('%s is not installed. --%s is '
							 'unavailable' % (info[0], arg)) 
Example 3
Project: nexa-controller-rpi   Author: vinnyspb   File: time_controller.py    MIT License 6 votes vote down vote up
def _fetch_location(self):
        conn = httplib.HTTPSConnection("freegeoip.io", timeout=60)
        conn.request("GET", "/json/")
        r1 = conn.getresponse()
        if r1.status != 200:
            raise Exception("Not 200 status in freegeoip API: " + str(r1.status))

        data1 = r1.read()
        decoded_json = json.loads(data1)

        if decoded_json is None:
            raise Exception("Can't decode freegeoip response as JSON: " + str(data1))

        self._latitude = decoded_json['latitude']
        self._longitude = decoded_json['longitude']
        logging.info("Fetched device position: (" + str(self._latitude) + ", " + str(self._longitude) + ")") 
Example 4
Project: Miscellaneous   Author: Shinpachi8   File: common.py    Apache License 2.0 6 votes vote down vote up
def is_https(url, port=None):
    """
    judge if the url is https request
    :url  the host, like www.iqiyi.com, without scheme
    """
    ssl._create_default_https_context = ssl._create_unverified_context
    if port is None: port = 443
    service = ''
    try:
        conn = httplib.HTTPSConnection(url, port, timeout=10)
        conn.request('HEAD', '/')
        conn.close()
        service = 'https'
    except Exception as e:
        print "[lib.common] [is_http] {}".format(repr(e))

    return service 
Example 5
Project: octopuscloud   Author: christianbaun   File: connection.py    Apache License 2.0 6 votes vote down vote up
def new_http_connection(self, host, is_secure):
        if self.use_proxy:
            host = '%s:%d' % (self.proxy, int(self.proxy_port))
        if host is None:
            host = self.server_name()
        boto.log.debug('establishing HTTP connection')
        if is_secure:
            if self.use_proxy:
                connection = self.proxy_ssl()
            elif self.https_connection_factory:
                connection = self.https_connection_factory(host)
            else:
                connection = httplib.HTTPSConnection(host)
        else:
            connection = httplib.HTTPConnection(host)
        if self.debug > 1:
            connection.set_debuglevel(self.debug)
        # self.connection must be maintained for backwards-compatibility
        # however, it must be dynamically pulled from the connection pool
        # set a private variable which will enable that
        if host.split(':')[0] == self.host and is_secure == self.is_secure:
            self._connection = (host, is_secure)
        return connection 
Example 6
Project: obscmdbench   Author: huaweicloud-obs   File: obsPyCmd.py    Apache License 2.0 6 votes vote down vote up
def create_connection(self):
        if self.isSecure:
            if not self.is_http2:
                if Util.compare_version(sys.version.split()[0], '2.7.9') >= 0:
                    self.connection = httplib.HTTPSConnection(self.host + ':443', timeout=self.timeout,
                                                              context=ssl.SSLContext(self.sslVersion))
                else:
                    self.connection = httplib.HTTPSConnection(self.host + ':443', timeout=self.timeout)
            else:
                import http2
                context = ssl.SSLContext(self.sslVersion)
                context.set_alpn_protocols(['h2'])
                # self.connection = HTTP20Connection(self.host, port=443, ssl_context=context, secure=True)
                self.connection = http2.HTTP20ConnectionWrapper(self.host, port=443, ssl_context=context, secure=True)
        elif not self.is_http2:
            self.connection = httplib.HTTPConnection(self.host + ':80', timeout=self.timeout)
        else:
            import http2
            # 使用http2.0
            self.connection = http2.HTTP20ConnectionWrapper(self.host, port=80)
            # self.connection = HTTP20Connection(self.host, port=80)
        logging.debug('create connection to host: ' + self.host) 
Example 7
Project: squeakspace   Author: eek6   File: https_fingerprint.py    GNU General Public License v3.0 6 votes vote down vote up
def connect(self):
        httplib.HTTPSConnection.connect(self)

        cert = self.sock.getpeercert(True) # get binary DER cert.

        if self.fingerprint_type == 'sha1':
            hash = hashlib.sha1()
        elif self.fingerprint_type == 'sha256':
            hash = hashlib.sha256()
        else:
            assert(False)

        hash.update(cert)
        peer_fingerprint = hash.hexdigest()

        if peer_fingerprint != self.fingerprint:
            raise HTTPSFingerprintException(self.fingerprint_type, self.fingerprint, peer_fingerprint) 
Example 8
Project: squeakspace   Author: eek6   File: db_sqlite3.py    GNU General Public License v3.0 6 votes vote down vote up
def get_node_connection(c, user_id, node_name):

    url, real_node_name, fingerprint_type, fingerprint = get_node_addr(c, user_id, node_name)

    (scheme, netloc, port) = parse_url(url)

    conn = None
    if scheme == 'http':
        conn = httplib.HTTPConnection(netloc, port)

    elif scheme == 'https':
        if fingerprint_type == None:
            # TODO: Ensure ssl validates the certificate.
            conn = httplib.HTTPSConnection(netloc, port)
        else:
            # Authenticate using stored fingerprint
            conn = https_fingerprint.HTTPSConnection_CheckFingerprint(netloc, port)
            conn.set_fingerprint(fingerprint_type, fingerprint)

    else:
        assert(False)

    return conn, url, real_node_name 
Example 9
Project: Subspace   Author: cpacia   File: network.py    MIT License 6 votes vote down vote up
def querySeed(self, seed):
        def query(seed):
            nodes = []
            c = httplib.HTTPSConnection(seed)
            c.request("GET", "/")
            response = c.getresponse()
            self.log.debug("Https response from %s: %s, %s" % (seed, response.status, response.reason))
            data = response.read()
            inbuffer = StringIO(data)
            f = gzip.GzipFile(mode='rb', fileobj=inbuffer)
            try:
                reread_data = f.read(len(data))
            finally:
                f.close()
            seeds = peerseeds.PeerSeeds()
            seeds.ParseFromString(reread_data)
            for seed in seeds.seed:
                tup = (str(seed.ip_address), seed.port)
                nodes.append(tup)
            return nodes
        d = defer.Deferred()
        reactor.callLater(0, d.callback, query(seed))
        return d 
Example 10
Project: CVE-2017-7494   Author: joxeankoret   File: httprelayclient.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, target):
        # Target comes as protocol://target:port/path
        self.target = target
        proto, host, path = target.split(':')
        host = host[2:]
        self.path = '/' + path.split('/', 1)[1]
        if proto.lower() == 'https':
            #Create unverified (insecure) context
            try:
                uv_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
                self.session = HTTPSConnection(host,context=uv_context)
            except AttributeError:
                #This does not exist on python < 2.7.11
                self.session = HTTPSConnection(host)
        else:
            self.session = HTTPConnection(host)
        self.lastresult = None 
Example 11
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 6 votes vote down vote up
def stripe_fetch(resource, method='GET', params=None, secret=settings.STRIPE_SECRET, prefix='/v1'):
    headers = {
        'Accept': 'application/json',
        'User-Agent': 'Clutch 1.0',
        'Authorization': 'Basic %s' % (base64.b64encode('%s:' % (secret,)),),
    }
    if params:
        flattened = {}
        for key, val in params.iteritems():
            if getattr(val, 'iteritems', None) is not None:
                for sub_key, sub_val in val.iteritems():
                    flattened['%s[%s]' % (key, sub_key)] = sub_val
            else:
                flattened[key] = val
        body = urllib.urlencode(flattened)
    else:
        body = ''
    with contextlib.closing(httplib.HTTPSConnection('api.stripe.com')) as conn:
        conn.request(method, prefix + resource, body, headers)
        raw_data = conn.getresponse().read()
    return simplejson.loads(raw_data) 
Example 12
Project: ironpython2   Author: IronLanguages   File: test_httplib.py    Apache License 2.0 6 votes vote down vote up
def test_host_port(self):
        # Check invalid host_port

        for hp in ("www.python.org:abc", "user:[email protected]"):
            self.assertRaises(httplib.InvalidURL, httplib.HTTPSConnection, hp)

        for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
                          "fe80::207:e9ff:fe9b", 8000),
                         ("www.python.org:443", "www.python.org", 443),
                         ("www.python.org:", "www.python.org", 443),
                         ("www.python.org", "www.python.org", 443),
                         ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
                         ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
                             443)):
            c = httplib.HTTPSConnection(hp)
            self.assertEqual(h, c.host)
            self.assertEqual(p, c.port) 
Example 13
Project: dataops   Author: xiaomatech   File: checkWebUI.py    Apache License 2.0 6 votes vote down vote up
def make_connection(host, port, https):
    try:
        conn = httplib.HTTPConnection(
            host, port) if not https else httplib.HTTPSConnection(host, port)
        conn.request("GET", "/")
        return conn.getresponse().status
    except ssl.SSLError:
        # got ssl error, lets try to use TLS1 protocol, maybe it will work
        try:
            tls1_conn = TLS1HTTPSConnection(host, port)
            tls1_conn.request("GET", "/")
            return tls1_conn.getresponse().status
        except Exception as e:
            print e
        finally:
            tls1_conn.close()
    except Exception as e:
        print e
    finally:
        conn.close()


#
# Main.
# 
Example 14
Project: pyblish-win   Author: pyblish   File: urllib2.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def https_open(self, req):
            return self.do_open(httplib.HTTPSConnection, req,
                context=self._context) 
Example 15
Project: pyblish-win   Author: pyblish   File: test_httplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testHTTPSConnectionSourceAddress(self):
        self.conn = httplib.HTTPSConnection(HOST, self.port,
                source_address=('', self.source_port))
        # We don't test anything here other the constructor not barfing as
        # this code doesn't deal with setting up an active running SSL server
        # for an ssl_wrapped connect() to actually return from. 
Example 16
Project: pyblish-win   Author: pyblish   File: test_httplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        if not hasattr(httplib, 'HTTPSConnection'):
            self.skipTest('ssl support required') 
Example 17
Project: pyblish-win   Author: pyblish   File: test_httplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_attributes(self):
        # simple test to check it's storing the timeout
        h = httplib.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
        self.assertEqual(h.timeout, 30) 
Example 18
Project: pyblish-win   Author: pyblish   File: test_httplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_networked(self):
        # Default settings: requires a valid cert from a trusted CA
        import ssl
        test_support.requires('network')
        with test_support.transient_internet('self-signed.pythontest.net'):
            h = httplib.HTTPSConnection('self-signed.pythontest.net', 443)
            with self.assertRaises(ssl.SSLError) as exc_info:
                h.request('GET', '/')
            self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED') 
Example 19
Project: pyblish-win   Author: pyblish   File: test_httplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_networked_trusted_by_default_cert(self):
        # Default settings: requires a valid cert from a trusted CA
        test_support.requires('network')
        with test_support.transient_internet('www.python.org'):
            h = httplib.HTTPSConnection('www.python.org', 443)
            h.request('GET', '/')
            resp = h.getresponse()
            content_type = resp.getheader('content-type')
            self.assertIn('text/html', content_type) 
Example 20
Project: pyblish-win   Author: pyblish   File: test_httplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_networked_good_cert(self):
        # We feed the server's cert as a validating cert
        import ssl
        test_support.requires('network')
        with test_support.transient_internet('self-signed.pythontest.net'):
            context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
            context.verify_mode = ssl.CERT_REQUIRED
            context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
            h = httplib.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
            h.request('GET', '/')
            resp = h.getresponse()
            server_string = resp.getheader('server')
            self.assertIn('nginx', server_string) 
Example 21
Project: pyblish-win   Author: pyblish   File: test_httplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_networked_bad_cert(self):
        # We feed a "CA" cert that is unrelated to the server's cert
        import ssl
        test_support.requires('network')
        with test_support.transient_internet('self-signed.pythontest.net'):
            context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
            context.verify_mode = ssl.CERT_REQUIRED
            context.load_verify_locations(CERT_localhost)
            h = httplib.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
            with self.assertRaises(ssl.SSLError) as exc_info:
                h.request('GET', '/')
            self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED') 
Example 22
Project: pyblish-win   Author: pyblish   File: test_httplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_local_unknown_cert(self):
        # The custom cert isn't known to the default trust bundle
        import ssl
        server = self.make_server(CERT_localhost)
        h = httplib.HTTPSConnection('localhost', server.port)
        with self.assertRaises(ssl.SSLError) as exc_info:
            h.request('GET', '/')
        self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED') 
Example 23
Project: pyblish-win   Author: pyblish   File: test_httplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_local_good_hostname(self):
        # The (valid) cert validates the HTTP hostname
        import ssl
        server = self.make_server(CERT_localhost)
        context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        context.verify_mode = ssl.CERT_REQUIRED
        context.load_verify_locations(CERT_localhost)
        h = httplib.HTTPSConnection('localhost', server.port, context=context)
        h.request('GET', '/nonexistent')
        resp = h.getresponse()
        self.assertEqual(resp.status, 404) 
Example 24
Project: pyblish-win   Author: pyblish   File: xmlrpclib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def make_connection(self, host):
        if self._connection and host == self._connection[0]:
            return self._connection[1]
        # create a HTTPS connection object from a host descriptor
        # host may be a string, or a (host, x509-dict) tuple
        try:
            HTTPS = httplib.HTTPSConnection
        except AttributeError:
            raise NotImplementedError(
                "your version of httplib doesn't support HTTPS"
                )
        else:
            chost, self._extra_headers, x509 = self.get_host_info(host)
            self._connection = host, HTTPS(chost, None, context=self.context, **(x509 or {}))
            return self._connection[1]

##
# Standard server proxy.  This class establishes a virtual connection
# to an XML-RPC server.
# <p>
# This class is available as ServerProxy and Server.  New code should
# use ServerProxy, to avoid confusion.
#
# @def ServerProxy(uri, **options)
# @param uri The connection point on the server.
# @keyparam transport A transport factory, compatible with the
#    standard transport class.
# @keyparam encoding The default encoding used for 8-bit strings
#    (default is UTF-8).
# @keyparam verbose Use a true value to enable debugging output.
#    (printed to standard output).
# @see Transport 
Example 25
Project: whatwaff   Author: SVelizDonoso   File: whatwaff.py    MIT License 5 votes vote down vote up
def test_https(self, url):
        parsed = urlparse(url)
        protocol = parsed[0]
        hostname = parsed[1]
        path = parsed[2]
        sslerror = False
            
        conn = httplib.HTTPSConnection(hostname)
        try:
            conn.request('GET', '/')
            res = conn.getresponse()
        except socket.gaierror:
            return {'supported': False, 'certvalid': False}
        except ssl.CertificateError:
            return {'supported': True, 'certvalid': False}
        except:
            sslerror = True

        if sslerror:
            conn = httplib.HTTPSConnection(hostname, timeout=5, context = ssl._create_unverified_context() )
            try:
                conn.request('GET', '/')
                res = conn.getresponse()
                return {'supported': True, 'certvalid': False}
            except:
                return {'supported': False, 'certvalid': False}

        return {'supported': True, 'certvalid': True} 
Example 26
Project: presto-admin   Author: prestosql   File: httpscacertconnection.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, host, port, key_file, cert_file, ca_file, strict, timeout=None):
        httplib.HTTPSConnection.__init__(self, host, port, key_file, cert_file, strict, timeout)
        self.key_file = key_file
        self.cert_file = cert_file
        self.ca_file = ca_file
        self.timeout = timeout 
Example 27
Project: openhatch   Author: campbe13   File: client.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, HTTPConnection=httplib.HTTPConnection,
                 HTTPSConnection=httplib.HTTPSConnection):
        self.HTTPConnection = HTTPConnection
        self.HTTPSConnection = HTTPSConnection 
Example 28
Project: openhatch   Author: campbe13   File: client.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _timeout_supported(self, ConnClass):
        if sys.version_info < (2, 7) and ConnClass in (
            httplib.HTTPConnection, httplib.HTTPSConnection): # pragma: no cover
            return False
        return True 
Example 29
Project: endpoints-tools   Author: cloudendpoints   File: generate-google-id-jwt.py    Apache License 2.0 5 votes vote down vote up
def main(args):
    """Request a Google ID token using a JWT."""
    params = urllib.urlencode({
        'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        'assertion': generate_jwt(args)})
    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    conn = httplib.HTTPSConnection("www.googleapis.com")
    conn.request("POST", "/oauth2/v4/token", params, headers)
    res = json.loads(conn.getresponse().read())
    conn.close()
    return res['id_token'] 
Example 30
Project: misp42splunk   Author: remg427   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, host, port=None, key_file=None, cert_file=None,
                 strict=None, timeout=None, proxy_info=None,
                 ca_certs=None, disable_ssl_certificate_validation=False):
        httplib.HTTPSConnection.__init__(self, host, port=port,
                                         key_file=key_file,
                                         cert_file=cert_file, strict=strict)
        self.timeout = timeout
        self.proxy_info = proxy_info
        if ca_certs is None:
            ca_certs = CA_CERTS
        self.ca_certs = ca_certs
        self.disable_ssl_certificate_validation = \
                disable_ssl_certificate_validation

    # The following two methods were adapted from https_wrapper.py, released
    # with the Google Appengine SDK at
    # http://googleappengine.googlecode.com/svn-history/r136/trunk/python/google/appengine/tools/https_wrapper.py
    # under the following license:
    #
    # Copyright 2007 Google Inc.
    #
    # Licensed under the Apache License, Version 2.0 (the "License");
    # you may not use this file except in compliance with the License.
    # You may obtain a copy of the License at
    #
    #     http://www.apache.org/licenses/LICENSE-2.0
    #
    # Unless required by applicable law or agreed to in writing, software
    # distributed under the License is distributed on an "AS IS" BASIS,
    # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    # See the License for the specific language governing permissions and
    # limitations under the License.
    # 
Example 31
Project: misp42splunk   Author: remg427   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, host, port=None, key_file=None, cert_file=None,
                     strict=None, timeout=None, proxy_info=None, ca_certs=None,
                     disable_ssl_certificate_validation=False):
            httplib.HTTPSConnection.__init__(self, host, port=port,
                                             key_file=key_file,
                                             cert_file=cert_file, strict=strict,
                                             timeout=timeout)
            self._fetch = _new_fixed_fetch(
                    not disable_ssl_certificate_validation)

    # Update the connection classes to use the Googel App Engine specific ones. 
Example 32
Project: misp42splunk   Author: remg427   File: sockshandler.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, proxytype, proxyaddr, proxyport=None, rdns=True, username=None, password=None, *args, **kwargs):
        self.proxyargs = (proxytype, proxyaddr, proxyport, rdns, username, password)
        httplib.HTTPSConnection.__init__(self, *args, **kwargs) 
Example 33
Project: nexa-controller-rpi   Author: vinnyspb   File: datadog_stat.py    MIT License 5 votes vote down vote up
def post_status(self, status):
        conn = httplib.HTTPSConnection("app.datadoghq.com", timeout=60)
        conn.request("GET", "/api/v1/validate?api_key=" + self._config.DATADOG_API_KEY)
        r1 = conn.getresponse()
        if r1.status != 200:
            raise Exception("Not 200 status in DataDog API login: " + str(r1.status))

        current_timestamp = int(time.time())
        if status:
            datadog_metric_value = self._config.DATADOG_ON_VALUE
        else:
            datadog_metric_value = self._config.DATADOG_OFF_VALUE

        headers = {"Content-type": "application/json"}
        post_data = '{ "series" : [{"metric":"' + self._config.DATATOG_METRIC_NAME + \
                    '", "points":[[' + str(current_timestamp) + \
                    ', ' + datadog_metric_value + ']], "type":"gauge", "host":"' + \
                    self._config.DATADOG_HOST_NAME + '", "tags\":[""]}]}'

        conn = httplib.HTTPSConnection("app.datadoghq.com", timeout=60)
        conn.request("POST", "/api/v1/series?api_key=" + self._config.DATADOG_API_KEY,
                     post_data,
                     headers)

        r1 = conn.getresponse()
        if r1.status != 202:
            raise Exception("Not 202 status in Datadog metric post: " + str(r1.status))

        return True 
Example 34
Project: pyomni   Author: taxpon   File: davlib.py    MIT License 5 votes vote down vote up
def __init__(self, *args, **kw):
        self.protocol = kw.pop('protocol')
        if self.protocol == "https":
            self.default_port = 443
        else:
            self.default_port = 80
            
        apply(httplib.HTTPSConnection.__init__, (self,) + args, kw) 
Example 35
Project: pyomni   Author: taxpon   File: davlib.py    MIT License 5 votes vote down vote up
def connect(self):
        if self.protocol == "https":
            httplib.HTTPSConnection.connect(self)
        else:
            httplib.HTTPConnection.connect(self) 
Example 36
Project: analyzer-website   Author: santiagolizardo   File: __init__.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, host, port=None, key_file=None, cert_file=None,
                 strict=None, timeout=None, proxy_info=None,
                 ca_certs=None, disable_ssl_certificate_validation=False):
        httplib.HTTPSConnection.__init__(self, host, port=port,
                                         key_file=key_file,
                                         cert_file=cert_file, strict=strict)
        self.timeout = timeout
        self.proxy_info = proxy_info
        if ca_certs is None:
            ca_certs = CA_CERTS
        self.ca_certs = ca_certs
        self.disable_ssl_certificate_validation = \
                disable_ssl_certificate_validation

    # The following two methods were adapted from https_wrapper.py, released
    # with the Google Appengine SDK at
    # http://googleappengine.googlecode.com/svn-history/r136/trunk/python/google/appengine/tools/https_wrapper.py
    # under the following license:
    #
    # Copyright 2007 Google Inc.
    #
    # Licensed under the Apache License, Version 2.0 (the "License");
    # you may not use this file except in compliance with the License.
    # You may obtain a copy of the License at
    #
    #     http://www.apache.org/licenses/LICENSE-2.0
    #
    # Unless required by applicable law or agreed to in writing, software
    # distributed under the License is distributed on an "AS IS" BASIS,
    # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    # See the License for the specific language governing permissions and
    # limitations under the License.
    # 
Example 37
Project: analyzer-website   Author: santiagolizardo   File: __init__.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, host, port=None, key_file=None, cert_file=None,
                     strict=None, timeout=None, proxy_info=None, ca_certs=None,
                     disable_ssl_certificate_validation=False):
            httplib.HTTPSConnection.__init__(self, host, port=port,
                                             key_file=key_file,
                                             cert_file=cert_file, strict=strict,
                                             timeout=timeout)
            self._fetch = _new_fixed_fetch(
                    not disable_ssl_certificate_validation)

    # Update the connection classes to use the Googel App Engine specific ones. 
Example 38
Project: octopuscloud   Author: christianbaun   File: xmlmanager.py    Apache License 2.0 5 votes vote down vote up
def _connect(self):
        if self.db_host:
            if self.enable_ssl:
                from httplib import HTTPSConnection as Connection
            else:
                from httplib import HTTPConnection as Connection

            self.connection = Connection(self.db_host, self.db_port) 
Example 39
Project: vulscan   Author: vulscanteam   File: sockshandler.py    MIT License 5 votes vote down vote up
def __init__(self, proxytype, proxyaddr, proxyport=None, rdns=True, username=None, password=None, *args, **kwargs):
        self.proxyargs = (proxytype, proxyaddr, proxyport, rdns, username, password)
        httplib.HTTPSConnection.__init__(self, *args, **kwargs) 
Example 40
Project: 2018-1-OSS-E7   Author: 18-1-SKKU-OSS   File: Updates.py    MIT License 5 votes vote down vote up
def check(self):
		h = http.HTTPSConnection("api.github.com")
		h.request("GET","/repos/vlachoudis/bCNC/releases/latest",None,{"User-Agent":"bCNC"})
		r = h.getresponse()
		if r.status == http.OK:
			data = json.loads(r.read().decode("utf-8"))
			latest_version = data["tag_name"]

			self.webversion.config(text=latest_version)
			self.published.config(text=data["published_at"])

			if self.isNewer(latest_version):
				self.webversion.config(background="LightGreen")
				self.checkButton.config(text=_("Download"),
						background="LightYellow",
						command=self.download)
				tkExtra.Balloon.set(self.checkButton, _("Open web browser to download bCNC"))
			else:
				self.checkButton.config(state=DISABLED)

		else:
			self.webversion.config(text=_("Error %d in connection")%(r.status))

		#self.laterButton.config(state=DISABLED)

		# Save today as lastcheck date
		Utils.config.set(Utils.__prg__,
			"lastcheck", str(int(time.time())))

	# ---------------------------------------------------------------------- 
Example 41
Project: seed-node-monitor   Author: BioMike   File: authproxy.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, service_url, service_name=None, timeout=HTTP_TIMEOUT, connection=None):
        self.__service_url = service_url
        self.__service_name = service_name
        self.__url = urlparse.urlparse(service_url)
        if self.__url.port is None:
            port = 80
        else:
            port = self.__url.port
        (user, passwd) = (self.__url.username, self.__url.password)
        try:
            user = user.encode('utf8')
        except AttributeError:
            pass
        try:
            passwd = passwd.encode('utf8')
        except AttributeError:
            pass
        authpair = user + b':' + passwd
        self.__auth_header = b'Basic ' + base64.b64encode(authpair)

        if connection:
            # Callables re-use the connection of the original proxy
            self.__conn = connection
        elif self.__url.scheme == 'https':
            self.__conn = httplib.HTTPSConnection(self.__url.hostname, port,
                                                  timeout=timeout)
        else:
            self.__conn = httplib.HTTPConnection(self.__url.hostname, port,
                                                 timeout=timeout) 
Example 42
Project: Lyff   Author: akashlevy   File: xmlmanager.py    MIT License 5 votes vote down vote up
def _connect(self):
        if self.db_host:
            if self.enable_ssl:
                from httplib import HTTPSConnection as Connection
            else:
                from httplib import HTTPConnection as Connection

            self.connection = Connection(self.db_host, self.db_port) 
Example 43
Project: nova   Author: ZhanHan   File: glance.py    Apache License 2.0 5 votes vote down vote up
def _create_connection(scheme, netloc):
    if scheme == 'https':
        conn = httplib.HTTPSConnection(netloc)
    else:
        conn = httplib.HTTPConnection(netloc)
    conn.connect()
    return conn 
Example 44
Project: insightconnect-plugins   Author: rapid7   File: mcafee.py    MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        httplib.HTTPSConnection.__init__(self, *args, **kwargs)

    # Override httplib.HTTPSConnection.connect() 
Example 45
Project: TAF   Author: couchbaselabs   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, host, port=None, key_file=None, cert_file=None,
                 strict=None, timeout=None, proxy_info=None):
        self.timeout = timeout
        self.proxy_info = proxy_info
        httplib.HTTPSConnection.__init__(self, host, port=port, key_file=key_file,
                                         cert_file=cert_file, strict=strict) 
Example 46
Project: sentry-python   Author: getsentry   File: test_httplib.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_httplib_misuse(sentry_init, capture_events):
    """HTTPConnection.getresponse must be called after every call to
    HTTPConnection.request. However, if somebody does not abide by
    this contract, we still should handle this gracefully and not
    send mixed breadcrumbs.

    Test whether our breadcrumbs are coherent when somebody uses HTTPConnection
    wrongly.
    """

    sentry_init()
    events = capture_events()

    conn = HTTPSConnection("httpbin.org", 443)
    conn.request("GET", "/anything/foo")

    with pytest.raises(Exception):
        # This raises an exception, because we didn't call `getresponse` for
        # the previous request yet.
        #
        # This call should not affect our breadcrumb.
        conn.request("POST", "/anything/bar")

    response = conn.getresponse()
    assert response._method == "GET"

    capture_message("Testing!")

    event, = events
    crumb, = event["breadcrumbs"]

    assert crumb["type"] == "http"
    assert crumb["category"] == "httplib"
    assert crumb["data"] == {
        "url": "https://httpbin.org/anything/foo",
        "method": "GET",
        "status_code": 200,
        "reason": "OK",
    } 
Example 47
Project: MSExchangeRelay   Author: mis-team   File: httprelayclient.py    GNU General Public License v3.0 5 votes vote down vote up
def initConnection(self):
        if self.target.scheme.lower() == "https":
            self.session = HTTPSConnection(self.targetHost,self.targetPort,context=ssl._create_unverified_context())
        else:
            self.session = HTTPConnection(self.targetHost, self.targetPort)
        self.lastresult = None
        if self.target.path == '':
            self.path = '/'
        else:
            self.path = self.target.path
        return True 
Example 48
Project: MSExchangeRelay   Author: mis-team   File: httprelayclient.py    GNU General Public License v3.0 5 votes vote down vote up
def initConnection(self):
        self.lastresult = None
        if self.target.path == '':
            self.path = '/'
        else:
            self.path = self.target.path
        try:
            uv_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
            self.session = HTTPSConnection(self.targetHost,self.targetPort, context=uv_context)
        except AttributeError:
            self.session = HTTPSConnection(self.targetHost,self.targetPort)
        return True 
Example 49
Project: ironpython2   Author: IronLanguages   File: urllib2.py    Apache License 2.0 5 votes vote down vote up
def https_open(self, req):
            return self.do_open(httplib.HTTPSConnection, req,
                context=self._context) 
Example 50
Project: ironpython2   Author: IronLanguages   File: test_httplib.py    Apache License 2.0 5 votes vote down vote up
def testHTTPSConnectionSourceAddress(self):
        self.conn = httplib.HTTPSConnection(HOST, self.port,
                source_address=('', self.source_port))
        # We don't test anything here other than the constructor not barfing as
        # this code doesn't deal with setting up an active running SSL server
        # for an ssl_wrapped connect() to actually return from.