Here are the examples of the python api http.client.HTTPSConnection taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
62 Examples
3
Example 1
Project: utorrentctl Source File: connection.py
def __init__( self, host, login, password, ssl = False ):
if ssl:
self._url = "https://{}/".format( host )
else:
self._url = "http://{}/".format( host )
self._request = urllib.request.Request( self._url )
if ssl:
self._connection = http.client.HTTPSConnection( host )
else:
self._connection = http.client.HTTPConnection( host )
self._connection.timeout = 10
self._request.add_header( "Authorization", "Basic " + b64encode( "{}:{}".format( login, password ).encode( "latin1" ) ).decode( "ascii" ) )
self._fetch_token( )
3
Example 2
def get_connection(self):
if self.prop.secure_http:
conn = http.client.HTTPSConnection(self.prop.api_url)
elif self.connection_properties.extra_headers is None \
or 'authorization' not in self.connection_properties.extra_headers:
conn = http.client.HTTPConnection(self.prop.api_url)
else:
raise ConnectionError(
'Refusing to send the authorization header over an insecure connection.')
return conn
3
Example 3
def test_networked_good_cert(self):
# We feed a CA cert that validates the server's cert
import ssl
support.requires('network')
with support.transient_internet('svn.python.org'):
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_REQUIRED
context.load_verify_locations(CACERT_svn_python_org)
h = client.HTTPSConnection('svn.python.org', 443, context=context)
h.request('GET', '/')
resp = h.getresponse()
self._check_svn_python_org(resp)
3
Example 4
def __api_call(self,method,params):
self.__nonce()
params['method'] = method
params['nonce'] = str(self.__nonce_v)
params = urllib.parse.urlencode(params)
headers = {"Content-type" : "application/x-www-form-urlencoded",
"Key" : self.__api_key,
"Sign" : self.__signature(params)}
conn = http.client.HTTPSConnection("btc-e.com")
conn.request("POST", "/tapi", params, headers)
response = conn.getresponse().read().decode()
data = json.loads(response)
conn.close()
return data
3
Example 5
Project: npmanager Source File: networkutils.py
def ping(url):
urlparts = urlparse(url)
total = 0
try:
if urlparts[0] == 'https':
h = HTTPSConnection(urlparts[1])
else:
h = HTTPConnection(urlparts[1])
start = timeit.default_timer()
h.request('GET', urlparts[2])
total = timeit.default_timer() - start
except (HTTPError, URLError):
total = None
else:
h.close()
return total
3
Example 6
def __init__(self, uri = 'api.kraken.com', timeout = 30):
""" Create an object for reusable connections.
:param uri: URI to connect to.
:type uri: str
:param timeout: blocking operations' timeout (in seconds).
:type timeout: int
:returns: TODO
:raises: TODO
"""
self.headers = {
'User-Agent': 'krakenex/0.1.2 (+https://github.com/veox/python3-krakenex)'
}
self.conn = http.client.HTTPSConnection(uri, timeout = timeout)
3
Example 7
Project: scrappy-ddns Source File: scrappyddns.py
def create_secure_conn():
"""Create and return HTTPSConnection to the push service."""
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_REQUIRED
ca_file = os.path.join(os.path.dirname(__file__), 'pushover-ca.pem')
context.load_verify_locations(ca_file)
return http.client.HTTPSConnection('api.pushover.net', 443, context=context)
3
Example 8
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 = client.HTTPSConnection('localhost', server.port, context=context)
h.request('GET', '/nonexistent')
resp = h.getresponse()
self.assertEqual(resp.status, 404)
del server
3
Example 9
Project: mqspeak Source File: sending.py
def fetch(self, channel, measurement):
"""!
@copydoc BaseSender::fetch()
"""
body = self.channelConvertMapping[channel].convert(measurement)
body.update({'created_at': measurement.time.isoformat(sep = ' ')})
body.update({'api_key': channel.apiKey})
bodyEncoded = urllib.parse.urlencode(body)
conn = http.client.HTTPSConnection("api.thingspeak.com", timeout = 30)
conn.request("POST", "/update", bodyEncoded)
response = conn.getresponse()
status = response.status
reason = response.reason
responseBytes = response.read()
conn.close()
return status, reason, responseBytes
3
Example 10
def make_connection(self, host):
if self._connection and host == self._connection[0]:
return self._connection[1]
if not hasattr(http.client, "HTTPSConnection"):
raise NotImplementedError(
"your version of http.client doesn't support HTTPS")
# create a HTTPS connection object from a host descriptor
# host may be a string, or a (host, x509-dict) tuple
chost, self._extra_headers, x509 = self.get_host_info(host)
self._connection = host, http.client.HTTPSConnection(chost,
None, **(x509 or {}))
return self._connection[1]
3
Example 11
Project: TrustRouter Source File: test_httplib.py
def test_local_good_hostname(self):
# The (valid) cert validates the HTTP hostname
import ssl
from test.ssl_servers import make_https_server
server = make_https_server(self, CERT_localhost)
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_REQUIRED
context.load_verify_locations(CERT_localhost)
h = client.HTTPSConnection('localhost', server.port, context=context)
h.request('GET', '/nonexistent')
resp = h.getresponse()
self.assertEqual(resp.status, 404)
3
Example 12
def _new_conn(self, host, port):
""" Create new connection
"""
if self.secure:
conn = httplib.HTTPSConnection(
host, port, timeout=self.http_socket_timeout)
else:
conn = httplib.HTTPConnection(
host, port, timeout=self.http_socket_timeout)
# Use self-defined Response class
conn.response_class = HTTPResponse
return conn
3
Example 13
@staticmethod
def checkUpdate():
try:
conn = httplib.HTTPSConnection("raw.githubusercontent.com", 443)
conn.request("GET", "/JonathanSalwan/ROPgadget/master/ropgadget/version.py")
except:
print("Can't connect to raw.githubusercontent.com")
return
d = conn.getresponse().read()
majorVersion = re.search("MAJOR_VERSION.+=.+(?P<value>[\d])", d).group("value")
minorVersion = re.search("MINOR_VERSION.+=.+(?P<value>[\d])", d).group("value")
webVersion = int("%s%s" %(majorVersion, minorVersion))
curVersion = int("%s%s" %(MAJOR_VERSION, MINOR_VERSION))
if webVersion > curVersion:
print("The version %s.%s is available. Currently, you use the version %d.%d." %(majorVersion, minorVersion, MAJOR_VERSION, MINOR_VERSION))
else:
print("Your version is up-to-date.")
3
Example 14
def setUp(self):
self.https_connection = mock.Mock(
spec=httplib.HTTPSConnection("host", "port"))
if self.connection_class is None:
raise ValueError(
"The connection_class attribute must be set firstly")
self.connection = self.connection_class(qy_access_key_id="access_key_id",
qy_secret_access_key="secret_access_key")
self.connection._new_conn = mock.Mock(
return_value=self.https_connection)
3
Example 15
Project: freeipa Source File: httptest.py
def send_request(self, method='POST', params=None):
"""
Send a request to HTTP server
:param key When not None, overrides default app_uri
"""
if params is not None:
# urlencode *can* take two arguments
# pylint: disable=too-many-function-args
params = urllib.parse.urlencode(params, True)
url = 'https://' + self.host + self.app_uri
headers = {'Content-Type' : self.content_type,
'Referer' : url}
conn = httplib.HTTPSConnection(self.host)
conn.request(method, self.app_uri, params, headers)
return conn.getresponse()
3
Example 16
def test_networked(self):
# Default settings: no cert verification is done
support.requires('network')
with support.transient_internet('svn.python.org'):
h = client.HTTPSConnection('svn.python.org', 443)
h.request('GET', '/')
resp = h.getresponse()
self._check_svn_python_org(resp)
3
Example 17
def setUp(self):
self.generator = S3.QueryStringAuthGenerator(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
if (self.generator.is_secure == True):
self.connection = http.client.HTTPSConnection(self.generator.server_name)
else:
self.connection = http.client.HTTPConnection(self.generator.server_name)
3
Example 18
def test_networked_bad_cert(self):
# We feed a "CA" cert that is unrelated to the server's cert
import ssl
support.requires('network')
with support.transient_internet('svn.python.org'):
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_REQUIRED
context.load_verify_locations(CERT_localhost)
h = client.HTTPSConnection('svn.python.org', 443, context=context)
with self.assertRaises(ssl.SSLError):
h.request('GET', '/')
3
Example 19
def get_connection(self):
if self.prop.secure_http:
conn = http.client.HTTPSConnection(self.prop.api_url)
elif self.prop.extra_headers is None \
or 'authorization' not in self.prop.extra_headers:
conn = http.client.HTTPConnection(self.prop.api_url)
else:
raise ConnectionError(
'Refusing to send the authorization header over an insecure connection.')
return conn
3
Example 20
def get_param(self, couple, param):
conn = http.client.HTTPSConnection("btc-e.com")
conn.request("GET", "/api/2/"+couple+"/"+param)
response = conn.getresponse().read().decode()
data = json.loads(response)
conn.close()
return data
3
Example 21
Project: aws-linux-system-tools Source File: aws-system-tools.py
def get_secure_connection(host, **options):
try:
http_proxy = get_proxy('http_proxy')
if http_proxy:
conn = HTTPConnection(*http_proxy, **options)
conn.set_tunnel(host, 443)
else:
https_proxy = get_proxy('https_proxy')
if https_proxy:
conn = HTTPSConnection(*https_proxy, **options)
conn.set_tunnel(host, 443)
else:
conn = HTTPSConnection(host, timeout=5)
except IOError:
log("Unable to connect to https://%s." % host)
raise
return conn
2
Example 22
Project: python-hpOneView Source File: connection.py
def get_connection(self):
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
if self._sslTrustAll is False:
context.verify_mode = ssl.CERT_REQUIRED
context.load_verify_locations(self._sslTrustedBundle)
if self._doProxy is False:
conn = http.client.HTTPSConnection(self._host,
context=context)
else:
conn = http.client.HTTPSConnection(self._proxyHost,
self._proxyPort,
context=context)
conn.set_tunnel(self._host, 443)
else:
context.verify_mode = ssl.CERT_NONE
if self._doProxy is False:
conn = http.client.HTTPSConnection(self._host,
context=context)
else:
conn = http.client.HTTPSConnection(self._proxyHost,
self._proxyPort,
context=context)
conn.set_tunnel(self._host, 443)
return conn
0
Example 23
def create():
"""
create and return instance that connect to facebook graph
"""
return httplib.HTTPSConnection('graph.facebook.com')
0
Example 24
def test_attributes(self):
# simple test to check it's storing the timeout
h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
self.assertEqual(h.timeout, 30)
0
Example 25
def test_local_bad_hostname(self):
# The (valid) cert doesn't validate the HTTP hostname
import ssl
server = self.make_server(CERT_fakehostname)
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_REQUIRED
context.load_verify_locations(CERT_fakehostname)
h = client.HTTPSConnection('localhost', server.port, context=context)
with self.assertRaises(ssl.CertificateError):
h.request('GET', '/')
# Same with explicit check_hostname=True
h = client.HTTPSConnection('localhost', server.port, context=context,
check_hostname=True)
with self.assertRaises(ssl.CertificateError):
h.request('GET', '/')
# With check_hostname=False, the mismatching is ignored
h = client.HTTPSConnection('localhost', server.port, context=context,
check_hostname=False)
h.request('GET', '/nonexistent')
resp = h.getresponse()
self.assertEqual(resp.status, 404)
del server
0
Example 26
def setup_connection(self):
self.http = HTTPSConnection(self.host, self.port)
0
Example 27
Project: TrustRouter Source File: test_httplib.py
@unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
'http.client.HTTPSConnection not defined')
def testHTTPSConnectionSourceAddress(self):
self.conn = client.HTTPSConnection(HOST, self.port,
source_address=('', self.source_port))
0
Example 28
def __call__(self, sender='', message='', link_url=None, icon=None, email=None, apikey=None):
data = {}
if email:
data['email'] = email[:1024]
else:
data['email'] = self._email[:1024]
data['notification[from_screen_name]'] = sender[:1024]
data['notification[message]'] = message[:1024]
if link_url:
data['notification[source_url]'] = link_url[:1024]
if icon:
data['notification[icon_url]'] = icon[:1024]
if apikey:
self.__set_path(apikey)
try:
conn = http.client.HTTPSConnection(self._apiurl)
conn.request("POST", self._path,
urllib.parse.urlencode(data), self._headers)
response = conn.getresponse()
if response.status == 200:
logger.info("Boxcar: Message %s %s successfully sent - %s %s" %
(sender, message, response.status, response.reason))
else:
logger.warning("Boxcar: Could not send message %s %s - %s %s" %
(sender, message, response.status, response.reason))
conn.close()
del(conn)
except Exception as e:
logger.warning(
"Could not send boxcar notification: {0}. Error: {1}".format(message, e))
0
Example 29
def request(verb, host, port, path, payload=None, https=False, headers=None, auth=None, redirect=True):
"""
Make an HTTP(S) request with the provided HTTP verb, host FQDN, port number, path,
payload, protocol, headers, and auth information. Return a response object with
payload, headers, JSON flag, and HTTP status number.
"""
if not headers:
headers = {}
headers["User-Agent"] = "GitSavvy Sublime Plug-in"
if auth:
username_password = "{}:{}".format(*auth).encode("ascii")
headers["Authorization"] = "Basic {}".format(b64encode(username_password).decode("ascii"))
connection = (http.client.HTTPSConnection(host, port)
if https
else http.client.HTTPConnection(host, port))
connection.request(verb, path, body=payload, headers=headers)
response = connection.getresponse()
response_payload = response.read()
response_headers = dict(response.getheaders())
status = response.status
is_json = "application/json" in response_headers["Content-Type"]
if is_json:
response_payload = json.loads(response_payload.decode("utf-8"))
response.close()
connection.close()
if redirect and verb == "GET" and status == 301 or status == 302:
return request_url(
verb,
response_headers["Location"],
headers=headers,
auth=auth
)
return Response(response_payload, response_headers, status, is_json)
0
Example 30
Project: Dynect-API-Python-Library Source File: DynectDNS.py
def connect(self):
"""
Establishes a connection to the REST API server as defined by the host,
port and ssl instance variables
"""
if self._token:
self._debug("Forcing logout from old session.\n")
orig_value = self.poll_incomplete
self.poll_incomplete = False
self.execute('/REST/Session', 'DELETE')
self.poll_incomplete = orig_value
self._token = None
self._conn = None
if self.ssl:
msg = "Establishing SSL connection to %s:%s\n" % (
self.host, self.port
)
self._debug(msg)
self._conn = HTTPSConnection(self.host, self.port)
else:
msg = "Establishing unencrypted connection to %s:%s\n" % (
self.host, self.port
)
self._debug(msg)
self._conn = HTTPConnection(self.host, self.port)
0
Example 31
Project: speedtest-cli Source File: speedtest_cli.py
def getBestServer(servers):
"""Perform a speedtest.net latency request to determine which
speedtest.net server has the lowest latency
"""
results = {}
for server in servers:
cuem = []
url = '%s/latency.txt' % os.path.dirname(server['url'])
urlparts = urlparse(url)
for i in range(0, 3):
try:
if urlparts[0] == 'https':
h = HTTPSConnection(urlparts[1])
else:
h = HTTPConnection(urlparts[1])
headers = {'User-Agent': user_agent}
start = timeit.default_timer()
h.request("GET", urlparts[2], headers=headers)
r = h.getresponse()
total = (timeit.default_timer() - start)
except (HTTPError, URLError, socket.error):
cuem.append(3600)
continue
text = r.read(9)
if int(r.status) == 200 and text == 'test=test'.encode():
cuem.append(total)
else:
cuem.append(3600)
h.close()
avg = round((sum(cuem) / 6) * 1000, 3)
results[avg] = server
fastest = sorted(results.keys())[0]
best = results[fastest]
best['latency'] = fastest
return best
0
Example 32
def _make_request(self, method, bucket='', key='', query_args={}, headers={}, data='', metadata={}):
server = ''
if bucket == '':
server = self.server
elif self.calling_format == CallingFormat.SUBDOMAIN:
server = "%s.%s" % (bucket, self.server)
elif self.calling_format == CallingFormat.VANITY:
server = bucket
else:
server = self.server
path = ''
if (bucket != '') and (self.calling_format == CallingFormat.PATH):
path += "/%s" % bucket
# add the slash after the bucket regardless
# the key will be appended if it is non-empty
path += "/%s" % urllib.parse.quote_plus(key)
# build the path_argument string
# add the ? in all cases since
# signature and credentials follow path args
if len(query_args):
path += "?" + query_args_hash_to_string(query_args)
is_secure = self.is_secure
host = "%s:%d" % (server, self.port)
while True:
if (is_secure):
connection = http.client.HTTPSConnection(host)
else:
connection = http.client.HTTPConnection(host)
final_headers = merge_meta(headers, metadata)
# add auth header
self._add_aws_auth_header(final_headers, method, bucket, key, query_args)
connection.request(method, path, data, final_headers)
resp = connection.getresponse()
if resp.status < 300 or resp.status >= 400:
return resp
# handle redirect
location = resp.getheader('location')
if not location:
return resp
# (close connection)
resp.read()
scheme, host, path, params, query, fragment \
= urllib.parse.urlparse(location)
if scheme == "http": is_secure = True
elif scheme == "https": is_secure = False
else: raise IOError("Not http/https: " + location)
if query: path += "?" + query
0
Example 33
def prepare(self, target, port, path, ssl):
conn_factory = httplib.HTTPSConnection if ssl else httplib.HTTPConnection
return conn_factory, target, port, path
0
Example 34
def __request__(self, req_type, url, username=None, password=None, value=None):
lurl = url.split('/')
# extract HOST http(s)://HOST/path/...
host = lurl[2]
# rebuild path from parts
purl = '/' + '/'.join(lurl[3:])
# select protocol: http or https
if url.startswith('https'):
conn = http.client.HTTPSConnection(host, timeout=self.timeout)
else:
conn = http.client.HTTPConnection(host, timeout=self.timeout)
# add headers
hdrs = {'Accept': 'text/plain'}
if username and password:
hdrs['Authorization'] = 'Basic ' + base64.b64encode(username + ':' + password)
if 'POST' == req_type:
data = urllib.parse.urlencode({'value': value})
data = data.encode('utf-8')
request = urllib.request.Request(url)
# adding charset parameter to the Content-Type header.
request.add_header("Content-Type","application/x-www-form-urlencoded;charset=utf-8")
f = urllib.request.urlopen(request, data)
if f.status in (http.client.OK, http.client.CREATED):
return f.read().decode('utf-8')
self.logger.warning("request failed: {0}: ".format(url))
# self.logger.debug("{0} response: {1} {2}".format(req_type, f.status, f.reason))
return None
elif 'PUT' == req_type:
conn.request(req_type, purl, body=value, headers=hdrs)
else: # 'GET' or 'DELETE'
conn.request(req_type, purl, headers=hdrs)
resp = conn.getresponse()
conn.close()
# success status: 201/Created for PUT request, else 200/Ok
if resp.status in (http.client.OK, http.client.CREATED):
return resp.read()
self.logger.warning("request failed for: {0}: ".format(url))
# self.logger.debug("{0} response: {1} {2}".format(req_type, resp.status, resp.reason))
return None
0
Example 35
Project: EventGhost Source File: ReleaseToGitHub.py
def DoTask(self):
buildSetup = self.buildSetup
appVer = buildSetup.appVersion
gitConfig = buildSetup.gitConfig
token = gitConfig["token"]
user = gitConfig["user"]
repo = gitConfig["repo"]
branch = gitConfig["branch"]
ref = 'heads/{0}'.format(branch)
setupFile = 'EventGhost_{0}_Setup.exe'.format(appVer)
setupPath = join(buildSetup.outputDir, setupFile)
chglogFile = "CHANGELOG.md"
chglogPath = join(buildSetup.outputDir, chglogFile)
print "reading changelog"
try:
f = open(chglogPath, 'r')
except IOError:
print "ERROR: couldn't read changelog file ({0}).".format(chglogFile)
return
else:
changelog = f.read()
f.close()
print "loading setup file"
try:
f = open(setupPath, 'rb')
except IOError:
print "ERROR: '{0}' not found.".format(setupFile)
return
else:
setupFileContent = f.read()
f.close()
gh = GitHub(token=token)
print "getting release info"
releaseExists = False
page = 1
while page > 0:
rc, data = gh.repos[user][repo].releases.get(
sha=branch,
per_page=100,
page=page
)
page = NextPage(gh)
if rc == 200:
for rel in data:
if rel['name'][1:] == appVer:
app = wx.GetApp()
win = app.GetTopWindow()
dlg = wx.MessageDialog(
win,
caption="Information",
message="Found an existing GitHub release matching"
" 'v{0}'\nOverwrite it?".format(appVer),
style=wx.YES_NO
)
if dlg.ShowModal() == wx.ID_NO:
return
releaseId = rel["id"]
uploadUrl = str(rel['upload_url'][:-13])
releaseExists = True
print "getting branch info"
rc, data = gh.repos[user][repo].branches[branch].get()
if rc != 200:
print "ERROR: couldn't get branch info."
return
commitSha = data['commit']['sha']
rc, data = gh.repos[user][repo].contents[chglogFile].get(ref=branch)
if rc == 200:
remoteChangelog = base64.decodestring(data["content"])
else:
remoteChangelog = None
if changelog != remoteChangelog:
print "getting commit referenced by branch"
rc, data = gh.repos[user][repo].git.commits[commitSha].get()
if rc != 200:
print "ERROR: couldn't get commit info."
return
treeSha = data['tree']['sha']
print "getting tree"
rc, data = gh.repos[user][repo].git.trees[treeSha].get()
if rc != 200:
print "ERROR: couldn't get tree info."
return
blob = None
print "getting blob for {0}".format(chglogFile)
for entry in data['tree']:
if entry['path'] == chglogFile and entry['type'] == 'blob':
blob = entry
break
if blob is None:
print "ERROR: couldn't get blob info."
return
print "posting new changelog"
body = {
'content': changelog,
'encoding': 'utf-8'
}
rc, data = gh.repos[user][repo].git.blobs.post(body=body)
if rc != 201:
print "ERROR: couldn't post new changelog contents."
return
print "posting tree"
newblob = {
'path': blob['path'],
'mode': blob['mode'],
'type': blob['type'],
'sha': data['sha']
}
body = {
'tree': [newblob],
'base_tree': treeSha
}
rc, data = gh.repos[user][repo].git.trees.post(body=body)
if rc != 201:
print "ERROR: couldn't post new tree."
return
newTreeSha = data['sha']
print "creating commit for changelog update"
body = {
'message': "Add changelog for v{0}".format(appVer),
'tree': newTreeSha,
'parents': [commitSha]
}
rc, data = gh.repos[user][repo].git.commits.post(body=body)
if rc != 201:
print "ERROR: couldn't create commit for changelog update."
return
newCommitSha = data['sha']
print "updating reference for branch to new commit"
body = {'sha': newCommitSha}
rc, data = gh.repos[user][repo].git.refs[ref].patch(body=body)
if rc != 200:
print "ERROR: couldn't update reference ({0}) with new commit.".format(ref)
return
if not releaseExists:
print "extracting changelog for this release"
relChglog = ''
chgLines = changelog.splitlines(True)
try:
for i in range(1, len(chgLines)):
if chgLines[i].startswith("## "):
break
else:
relChglog += chgLines[i]
except IndexError:
pass
relChglog = relChglog.strip()
print "creating release"
body = {'tag_name': 'v{0}'.format(appVer),
'target_commitish': newCommitSha,
'name': 'v{0}'.format(appVer),
'body': relChglog,
#'draft': False,
'prerelease': ("-" in self.buildSetup.appVersion)
}
rc, data = gh.repos[user][repo].releases.post(body=body)
if rc != 201:
print "ERROR: couldn't create a release on GitHub."
return
uploadUrl = str(data['upload_url'][:-13])
else:
print 'deleting existing asset'
rc, data = gh.repos[user][repo].releases[releaseId].assets.get()
if rc == 200:
for asset in data:
if asset["name"] == setupFile:
rc, data = gh.repos[user][repo].releases.\
assets[asset["id"]].delete()
if rc != 204:
print "ERROR: couldn't delete existing asset."
return
break
print "uploading setup file"
url = uploadUrl + '?name={0}'.format(setupFile)
headers = {'content-type': 'application/octet-stream',
'authorization': 'Token {0}'.format(token),
'accept': 'application/vnd.github.v3+json',
'user-agent': 'agithub/v2.0'}
conn = http.client.HTTPSConnection('uploads.github.com')
conn.request('POST', url, setupFileContent, headers)
response = conn.getresponse()
status = response.status
conn.close()
if status != 201:
print "ERROR: couldn't upload installer file to GitHub."
return
0
Example 36
def _connect(self):
"""Establish HTTPS Connection"""
self.connection = HTTPSConnection(*self.sig[1:], timeout=30,
context=self.SSLCONTEXT)
0
Example 37
def retry_using_http_NTLM_auth(self, req, auth_header_field, realm, headers):
user, pw = self.passwd.find_user_password(realm, req.get_full_url())
debug_output(user, pw)
if pw is not None:
user_parts = user.split('\\', 1)
if len(user_parts) == 1:
UserName = user_parts[0]
DomainName = ''
type1_flags = ntlm.NTLM_ttype1_FLAGS & ~ntlm.NTLM_NegotiateOemDomainSupplied
else:
DomainName = user_parts[0].upper()
UserName = user_parts[1]
type1_flags = ntlm.NTLM_ttype1_FLAGS
# ntlm secures a socket, so we must use the same socket for the complete handshake
debug_output(hex(type1_flags))
headers = dict(req.headers)
headers.update(req.unredirected_hdrs)
auth = 'NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(user, type1_flags)
if req.headers.get(self.auth_header, None) == auth:
debug_output("no auth_header")
return None
headers[self.auth_header] = auth
host = req.get_host()
if not host:
raise urllib.request.URLError('no host given')
h = None
if req.get_full_url().startswith('https://'):
h = http.client.HTTPSConnection(host) # will parse host:port
else:
h = http.client.HTTPConnection(host) # will parse host:port
# we must keep the connection because NTLM authenticates the connection, not single requests
headers["Connection"] = "Keep-Alive"
headers = dict((name.title(), val) for name, val in list(headers.items()))
h.request(req.get_method(), req.get_selector(), req.data, headers)
r = h.getresponse()
r.begin()
r._safe_read(int(r.getheader('content-length')))
debug_output('data read')
try:
if r.getheader('set-cookie'):
# this is important for some web applications that store authentication-related info in cookies (it took a long time to figure out)
headers['Cookie'] = r.getheader('set-cookie')
debug_output('cookie: ', headers['Cookie'])
except TypeError:
debug_output('no cookie')
pass
r.fp = None # remove the reference to the socket, so that it can not be closed by the response object (we want to keep the socket open)
auth_header_value = r.getheader(auth_header_field, None)
debug_output(r.headers)
debug_output(auth_header_field, ': ', auth_header_value)
(ServerChallenge, NegotiateFlags) = ntlm.parse_NTLM_CHALLENGE_MESSAGE(auth_header_value[5:])
debug_output('server c ', ServerChallenge, ' server flags ', hex(NegotiateFlags))
auth = 'NTLM %s' % ntlm.create_NTLM_AUTHENTICATE_MESSAGE(ServerChallenge, UserName, DomainName, pw, NegotiateFlags)
headers[self.auth_header] = auth
debug_output('auth ', auth)
headers["Connection"] = "Close"
headers = dict((name.title(), val) for name, val in list(headers.items()))
try:
h.request(req.get_method(), req.get_selector(), req.data, headers)
# none of the configured handlers are triggered, for example redirect-responses are not handled!
response = h.getresponse()
debug_output('data 3 read')
def notimplemented():
raise NotImplementedError
response.readline = notimplemented
return addinfourl(response, response.msg, req.get_full_url())
except socket.error as err:
raise urllib.request.URLError(err)
else:
return None
0
Example 38
Project: KSP Source File: upstream.py
def call_upstream(self, request, device):
"""proxy a request to the originally intended server, returns a http response"""
if device.is_provisional(): # not yet allowed access upstream
logging.warn("device %s may not connect to upstream (provisional)")
return None
upstream_host = self._upstream_host(request, device)
conn = device.connections.get(upstream_host)
if not conn:
# it's very unlikely a device will shoot two requests to the same service at the same time, just after KSP started
# so we should be reasonable safe creating the connection without locking
conn = HTTPSConnection(upstream_host, context = device.ssl_context(upstream_host))
conn.last_call = 0
conn._lock = RLock()
logging.info("created upstream connection to %s for %s", upstream_host, device)
conn = device.connections.setdefault(upstream_host, conn) # just in case...
with conn._lock:
# uuuuugly... but this way we make sure device requests don't step on each other's toes too much
del request.headers['Host']
request.headers['Host'] = conn.host
# yeah, let's not leave these around
del request.headers['X-Forwarded-For']
del request.headers['X-Forwarded-Host']
del request.headers['X-Forwarded-Server']
# we check the connection state because otherwise we might mess up another request in process
if conn.sock:
if conn._HTTPConnection__state != _CS_IDLE:
raise Exception("acquired connection but it's not idle!", upstream_host, str(device))
if request.started_at - conn.last_call > _IDLE: # avoid socket timeouts
conn.close()
# finally, actually call upstream
response = self._call_upstream(conn, request)
response = wrap_response(response)
http_debug("got response %s", response)
return response
0
Example 39
Project: azure-linux-extensions Source File: httpclient.py
def get_connection(self, request):
''' Create connection for the request. '''
protocol = request.protocol_override \
if request.protocol_override else self.protocol
target_host = request.host
target_port = HTTP_PORT if protocol == 'http' else HTTPS_PORT
if not self.use_httplib:
import azure.http.winhttp
connection = azure.http.winhttp._HTTPConnection(
target_host, cert_file=self.cert_file, protocol=protocol)
proxy_host = self.proxy_host
proxy_port = self.proxy_port
else:
if ':' in target_host:
target_host, _, target_port = target_host.rpartition(':')
if self.proxy_host:
proxy_host = target_host
proxy_port = target_port
host = self.proxy_host
port = self.proxy_port
else:
host = target_host
port = target_port
if protocol == 'http':
connection = HTTPConnection(host, int(port))
else:
connection = HTTPSConnection(
host, int(port), cert_file=self.cert_file)
if self.proxy_host:
headers = None
if self.proxy_user and self.proxy_password:
auth = base64.encodestring(
"{0}:{1}".format(self.proxy_user, self.proxy_password))
headers = {'Proxy-Authorization': 'Basic {0}'.format(auth)}
connection.set_tunnel(proxy_host, int(proxy_port), headers)
return connection
0
Example 40
def __call__(self, event='', description='', priority=None, url=None, apikey=None, application='SmartHome'):
data = {}
headers = {'User-Agent': "SmartHome.py", 'Content-Type': "application/x-www-form-urlencoded"}
data['event'] = event[:1000].encode()
data['description'] = description[:1000].encode()
data['application'] = application[:256].encode()
if apikey:
data['apikey'] = apikey
else:
data['apikey'] = self._apikey
if priority:
data['priority'] = priority
if url:
data['url'] = url[:2000]
try:
conn = http.client.HTTPSConnection(self._host, timeout=4)
conn.request("POST", self._api, urllib.parse.urlencode(data), headers)
resp = conn.getresponse()
conn.close()
if (resp.status == 200):
logger.debug("NMA returns: Notification submitted.")
elif (resp.status == 400):
logger.warning("NMA returns: The data supplied is in the wrong format, invalid length or null.")
elif (resp.status == 401):
logger.warning("NMA returns: None of the API keys provided were valid.")
elif (resp.status == 402):
logger.warning("NMA returns: Maximum number of API calls per hour exceeded.")
elif (resp.status == 500):
logger.warning("NMA returns: Internal server error. Please contact our support if the problem persists.")
else:
logger.error("NAME returns unknown HTTP status code = {0}".format(resp.status))
except Exception as e:
logger.warning("Could not send NMA notification: {0}. Error: {1}".format(event, e))
0
Example 41
Project: hprose-python Source File: httpclient.py
def _sendAndReceive(self, data):
header = {'Content-Type': 'application/hprose'}
header['Host'] = self.__host
if (self.__port != 80):
header['Host'] += ':' + str(self.__port)
cookie = _getCookie(self.__host, self.__path, self.__scheme == 'https')
if cookie != '':
header['Cookie'] = cookie
if self.keepAlive:
header['Connection'] = 'keep-alive'
header['Keep-Alive'] = str(self.keepAliveTimeout)
else:
header['Connection'] = 'close'
for name in self.__header: header[name] = self.__header[name]
if self.__proxy == None:
if self.__scheme == 'https':
httpclient = http.client.HTTPSConnection(self.__ip, self.__port, timeout = self.timeout)
else:
httpclient = http.client.HTTPConnection(self.__ip, self.__port, timeout = self.timeout)
else:
if self.__proxy['scheme'] == 'https':
httpclient = http.client.HTTPSConnection(self.__proxy['ip'], self.__proxy['port'], timeout = self.timeout)
else:
httpclient = http.client.HTTPConnection(self.__proxy['ip'], self.__proxy['port'], timeout = self.timeout)
if self.__proxy == None:
path = urllib.parse.urlunsplit(('', '', self.__path, self.__query, self.__fragment))
else:
path = self._uri
httpclient.request('POST', path, data, header)
resp = httpclient.getresponse()
if resp.status == 200:
cookieList = resp.getheader('set-cookie', '').split(',')
cookieList.extend(resp.getheader('set-cookie2', '').split(','))
_setCookie(cookieList, self.__host)
data = resp.read()
httpclient.close()
return data
else:
httpclient.close()
raise HproseException('%d:%s' % (resp.status, resp.reason))
0
Example 42
Project: TrustRouter Source File: test_httplib.py
def test_local_bad_hostname(self):
# The (valid) cert doesn't validate the HTTP hostname
import ssl
from test.ssl_servers import make_https_server
server = make_https_server(self, CERT_fakehostname)
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_REQUIRED
context.load_verify_locations(CERT_fakehostname)
h = client.HTTPSConnection('localhost', server.port, context=context)
with self.assertRaises(ssl.CertificateError):
h.request('GET', '/')
# Same with explicit check_hostname=True
h = client.HTTPSConnection('localhost', server.port, context=context,
check_hostname=True)
with self.assertRaises(ssl.CertificateError):
h.request('GET', '/')
# With check_hostname=False, the mismatching is ignored
h = client.HTTPSConnection('localhost', server.port, context=context,
check_hostname=False)
h.request('GET', '/nonexistent')
resp = h.getresponse()
self.assertEqual(resp.status, 404)
0
Example 43
def __call__(self, event='', description='', priority=None, url=None, apikey=None, application='SmartHome'):
data = {}
headers = {'User-Agent': "SmartHome.py", 'Content-Type': "application/x-www-form-urlencoded"}
data['event'] = event[:1024].encode()
data['description'] = description[:10000].encode()
data['application'] = application[:256].encode()
if apikey:
data['apikey'] = apikey
else:
data['apikey'] = self._apikey.encode()
if priority:
data['priority'] = priority
if url:
data['url'] = url[:512]
try:
conn = http.client.HTTPSConnection(self._host, timeout=4)
conn.request("POST", self._api, urllib.parse.urlencode(data), headers)
resp = conn.getresponse()
conn.close()
if resp.status != 200:
raise Exception("{} {}".format(resp.status, resp.reason))
except Exception as e:
logger.warning("Could not send prowl notification: {0}. Error: {1}".format(event, e))
0
Example 44
def __get__(self, obj=None, objtype=None):
if self.id in self.responses:
return self.responses[self.id]
if self.ssl:
connection = http.client.HTTPSConnection(
self.domain,
port=self.port,
timeout=self.timeout
)
else:
connection = http.client.HTTPConnection(
self.domain,
port=self.port,
timeout=self.timeout
)
try:
connection.request('HEAD', '/', None, headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; rv:36.0)' +
'Gecko/200101 Firefox/36.0'
}
)
response = connection.getresponse()
except:
response = None
connection.close()
self.responses[self.id] = response
return response
0
Example 45
Project: bCNC Source File: Updates.py
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())))
0
Example 46
def __init__(self , token):
self.token = token
self.httpClient = HTTPSConnection(vs.HTTP_URL, vs.HTTP_PORT)
0
Example 47
Project: isso Source File: http.py
def __enter__(self):
host, port, ssl = urlsplit(self.host)
http = httplib.HTTPSConnection if ssl else httplib.HTTPConnection
for _ in range(MAX_RETRY_COUNT):
self.con = http(host, port, timeout=self.timeout)
try:
self.con.request(self.method, self.path, headers=self.headers)
except (httplib.HTTPException, socket.error) as e:
return None
try:
resp = self.con.getresponse()
if resp.status == 301:
location = resp.getheader('Location')
if location:
self.con.close()
self.path = urlparse(location).path
else:
return None
else:
return resp
except (httplib.HTTPException, socket.timeout, socket.error):
return None
0
Example 48
Project: headphones Source File: http.py
def emit(self, record):
"""
Emit a record.
Send the record to the Web server as a percent-encoded dictionary
:param record: The record to be emitted.
"""
try:
import http.client, urllib.parse
host = self.host
if self.secure:
h = http.client.HTTPSConnection(host)
else:
h = http.client.HTTPConnection(host)
url = self.url
data = urllib.parse.urlencode(self.mapLogRecord(record))
if self.method == "GET":
if (url.find('?') >= 0):
sep = '&'
else:
sep = '?'
url = url + "%c%s" % (sep, data)
h.putrequest(self.method, url)
# support multiple hosts on one IP address...
# need to strip optional :port from host, if present
i = host.find(":")
if i >= 0:
host = host[:i]
h.putheader("Host", host)
if self.method == "POST":
h.putheader("Content-type",
"application/x-www-form-urlencoded")
h.putheader("Content-length", str(len(data)))
if self.credentials:
import base64
s = ('u%s:%s' % self.credentials).encode('utf-8')
s = 'Basic ' + base64.b64encode(s).strip()
h.putheader('Authorization', s)
h.endheaders(data if self.method == "POST" else None)
h.getresponse() #can't do anything with the result
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
0
Example 49
def is_running(self):
"""Try to connect the api server websocket to see if env is running.
"""
name = self.config.get_env_name()
jenv = os.path.join(
self.config.juju_home, "environments", "%s.jenv" % name)
if not os.path.exists(jenv):
return False
with open(jenv) as handle:
data = yaml.safe_load(handle.read())
if not data:
return False
conf = data.get('bootstrap-config')
if not conf['type'] in ('manual', 'null'):
return False
conn = httplib.HTTPSConnection(
conf['bootstrap-host'], port=17070, timeout=1.2)
try:
conn.request("GET", "/")
return True
except socket.error:
return False
0
Example 50
Project: xhtml2pdf Source File: util.py
def __init__(self, uri, basepath=None):
self.basepath = basepath
self.mimetype = None
self.file = None
self.data = None
self.uri = None
self.local = None
self.tmp_file = None
uri = uri or str()
if type(uri) != str:
uri = uri.decode("utf-8")
log.debug("FileObject %r, Basepath: %r", uri, basepath)
# Data URI
if uri.startswith("data:"):
m = _rx_datauri.match(uri)
self.mimetype = m.group("mime")
self.data = base64.b64decode(m.group("data").encode("utf-8"))
else:
# Check if we have an external scheme
if basepath and not urlparse.urlparse(uri).scheme:
urlParts = urlparse.urlparse(basepath)
else:
urlParts = urlparse.urlparse(uri)
log.debug("URLParts: {}".format((urlParts, urlParts.scheme)))
if urlParts.scheme == 'file':
if basepath and uri.startswith('/'):
uri = urlparse.urljoin(basepath, uri[1:])
urlResponse = urllib2.urlopen(uri)
self.mimetype = urlResponse.info().get(
"Content-Type", '').split(";")[0]
self.uri = urlResponse.geturl()
self.file = urlResponse
# Drive letters have len==1 but we are looking
# for things like http:
elif urlParts.scheme in ('http', 'https'):
log.debug("Sending request for {} with httplib".format(uri))
# External data
if basepath:
uri = urlparse.urljoin(basepath, uri)
log.debug("Uri parsed: {}".format(uri))
#path = urlparse.urlsplit(url)[2]
#mimetype = getMimeType(path)
# Using HTTPLIB
server, path = urllib2.splithost(uri[uri.find("//"):])
if uri.startswith("https://"):
conn = httplib.HTTPSConnection(server)
else:
conn = httplib.HTTPConnection(server)
conn.request("GET", path)
r1 = conn.getresponse()
# log.debug("HTTP %r %r %r %r", server, path, uri, r1)
if (r1.status, r1.reason) == (200, "OK"):
self.mimetype = r1.getheader(
"Content-Type", '').split(";")[0]
self.uri = uri
log.debug("here")
if r1.getheader("content-encoding") == "gzip":
import gzip
self.file = gzip.GzipFile(
mode="rb", fileobj=six.StringIO(r1.read()))
else:
self.file = r1
else:
log.debug("Received non-200 status: {}".format((r1.status, r1.reason)))
try:
urlResponse = urllib2.urlopen(uri)
except urllib2.HTTPError as e:
log.error("Could not process uri: {}".format(e))
return
self.mimetype = urlResponse.info().get(
"Content-Type", '').split(";")[0]
self.uri = urlResponse.geturl()
self.file = urlResponse
else:
log.debug("Unrecognized scheme, assuming local file path")
# Local data
if basepath:
uri = os.path.normpath(os.path.join(basepath, uri))
if os.path.isfile(uri):
self.uri = uri
self.local = uri
self.setMimeTypeByName(uri)
if self.mimetype.startswith('text'):
self.file = open(uri, "r") #removed bytes... lets hope it goes ok :/
else:
self.file = open(uri, "rb") #removed bytes... lets hope it goes ok :/