本文整理匯總了Python中six.moves.http_client.HTTPConnection方法的典型用法代碼示例。如果您正苦於以下問題:Python http_client.HTTPConnection方法的具體用法?Python http_client.HTTPConnection怎麽用?Python http_client.HTTPConnection使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類six.moves.http_client
的用法示例。
在下文中一共展示了http_client.HTTPConnection方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _password_client
# 需要導入模塊: from six.moves import http_client [as 別名]
# 或者: from six.moves.http_client import HTTPConnection [as 別名]
def _password_client(self, body=None, headers=None, decode=True):
"""Client for the Password Server."""
port = CONF.cloudstack.password_server_port
with contextlib.closing(http_client.HTTPConnection(
self._metadata_host, port, timeout=TIMEOUT)) as connection:
try:
connection.request("GET", "/", body=body, headers=headers)
response = connection.getresponse()
except http_client.HTTPException as exc:
LOG.error("Request failed: %s", exc)
raise
content = response.read()
if decode:
content = encoding.get_as_string(content)
if response.status != 200:
raise http_client.HTTPException(
"%(status)s %(reason)s - %(message)r",
{"status": response.status, "reason": response.reason,
"message": content})
return content
示例2: testDataPaths_disableAllCaching
# 需要導入模塊: from six.moves import http_client [as 別名]
# 或者: from six.moves.http_client import HTTPConnection [as 別名]
def testDataPaths_disableAllCaching(self):
"""Test the format of the /data/runs endpoint."""
for path in ('/data/runs',
'/data/logdir',
'/data/scalars?run=run1&tag=simple_values',
'/data/scalars?run=run1&tag=simple_values&format=csv',
'/data/images?run=run1&tag=image',
'/data/individualImage?run=run1&tag=image&index=0',
'/data/audio?run=run1&tag=audio',
'/data/run_metadata?run=run1&tag=test%20run'):
connection = http_client.HTTPConnection(
'localhost', self._server.server_address[1])
connection.request('GET', path)
response = connection.getresponse()
self.assertEqual(response.status, 200, msg=path)
self.assertEqual(response.getheader('Expires'), '0', msg=path)
response.read()
connection.close()
示例3: _get_version
# 需要導入模塊: from six.moves import http_client [as 別名]
# 或者: from six.moves.http_client import HTTPConnection [as 別名]
def _get_version(self, master):
if master is not None:
conn = None
host, port = master.split(':', 2)
port = int(port)
try:
conn = HTTPConnection(host, port, timeout=self._timeout)
conn.request('GET', '/version')
resp = conn.getresponse()
if resp.status < 200 or resp.status >= 300:
return
return json.loads(resp.read().decode('utf-8'))['version']
except Exception:
logger.exception('Error')
pass
finally:
if conn:
conn.close()
示例4: check_for_delay
# 需要導入模塊: from six.moves import http_client [as 別名]
# 或者: from six.moves.http_client import HTTPConnection [as 別名]
def check_for_delay(self, verb, path, username=None):
body = jsonutils.dumps({"verb": verb, "path": path})
headers = {"Content-Type": "application/json"}
conn = http_client.HTTPConnection(self.limiter_address)
if username:
conn.request("POST", "/%s" % (username), body, headers)
else:
conn.request("POST", "/", body, headers)
resp = conn.getresponse()
if 200 >= resp.status < 300:
return None, None
return resp.getheader("X-Wait-Seconds"), resp.read() or None
# Note: This method gets called before the class is instantiated,
# so this must be either a static method or a class method. It is
# used to develop a list of limits to feed to the constructor.
# This implementation returns an empty list, since all limit
# decisions are made by a remote server.
示例5: remote_canari_transform_runner
# 需要導入模塊: from six.moves import http_client [as 別名]
# 或者: from six.moves.http_client import HTTPConnection [as 別名]
def remote_canari_transform_runner(host, base_path, transform, entities, parameters, limits, is_ssl=False):
c = http_client.HTTPSConnection(host) if is_ssl else http_client.HTTPConnection(host)
m = MaltegoTransformRequestMessage()
for e in entities:
m += e
for p in parameters:
m += p
m += limits
msg = MaltegoMessage(message=m).render(encoding='utf-8')
path = re.sub(r'/+', '/', '/'.join([base_path, transform]))
if is_debug_exec_mode():
sys.stderr.write("Sending following message to {}{}:\n{}\n\n".format(host, path, msg))
c.request('POST', path, msg, headers={'Content-Type': 'application/xml'})
return c.getresponse()
示例6: test_http_over_https
# 需要導入模塊: from six.moves import http_client [as 別名]
# 或者: from six.moves.http_client import HTTPConnection [as 別名]
def test_http_over_https(self):
if self.scheme != 'https':
return self.skip('skipped (not running HTTPS)... ')
# Try connecting without SSL.
conn = HTTPConnection('%s:%s' % (self.interface(), self.PORT))
conn.putrequest('GET', '/', skip_host=True)
conn.putheader('Host', self.HOST)
conn.endheaders()
response = conn.response_class(conn.sock, method='GET')
try:
response.begin()
self.assertEqual(response.status, 400)
self.body = response.read()
self.assertBody('The client sent a plain HTTP request, but this '
'server only speaks HTTPS on this port.')
except socket.error:
e = sys.exc_info()[1]
# "Connection reset by peer" is also acceptable.
if e.errno != errno.ECONNRESET:
raise
示例7: _CreateDB
# 需要導入模塊: from six.moves import http_client [as 別名]
# 或者: from six.moves.http_client import HTTPConnection [as 別名]
def _CreateDB(self):
"""This method is idempotent. If the DB already exists it will simply
return a 200 code without re-creating it.
"""
successful_http_request_codes = [200, 202, 204]
header = {'Content-type': 'application/x-www-form-urlencoded',
'Accept': 'text/plain'}
params = urllib.parse.urlencode(
{'q': 'CREATE DATABASE ' + self.influx_db_name})
conn = httplib.HTTPConnection(self.influx_uri)
conn.request('POST', '/query?' + params, headers=header)
response = conn.getresponse()
conn.close()
if response.status in successful_http_request_codes:
logging.debug('Success! %s DB Created', self.influx_db_name)
else:
logging.error('%d Request could not be completed due to: %s',
response.status, response.reason)
raise httplib.HTTPException
示例8: __init__
# 需要導入模塊: from six.moves import http_client [as 別名]
# 或者: from six.moves.http_client import HTTPConnection [as 別名]
def __init__(self, path, host='localhost', port=None, strict=None,
timeout=None):
if six.PY3:
http_client.HTTPConnection.__init__(self, host, port=port,
timeout=timeout)
else:
http_client.HTTPConnection.__init__(self, host, port=port,
strict=strict,
timeout=timeout)
self.path = path
示例9: check_server
# 需要導入模塊: from six.moves import http_client [as 別名]
# 或者: from six.moves.http_client import HTTPConnection [as 別名]
def check_server(host, port, path_info='/', timeout=3, retries=30):
"""Perform a request until the server reply"""
if retries < 0:
return 0
conn = http_client.HTTPConnection(host, port, timeout=timeout)
time.sleep(.3)
for i in range(retries):
try:
conn.request('GET', path_info)
res = conn.getresponse()
return res.status
except (socket.error, http_client.HTTPException):
time.sleep(.3)
return 0
示例10: open
# 需要導入模塊: from six.moves import http_client [as 別名]
# 或者: from six.moves.http_client import HTTPConnection [as 別名]
def open(self):
if self.request == 'hyper':
if self.http2:
self.__http = hyper.HTTP20Connection(self.host, self.port, proxy_host=self.realhost, proxy_port=self.realport, proxy_headers=self.proxy_headers)
else:
self.__http = hyper.HTTPConnection(self.host, self.port, proxy_host=self.realhost, proxy_port=self.realport, proxy_headers=self.proxy_headers)
elif self.request == 'httpx':
if self.http2:
self.__http = httpx.AsyncClient(base_url='%s://%s' % (self.scheme, self.host), http2=self.http2)
else:
self.__http = httpx.Client(base_url='%s://%s' % (self.scheme, self.host))
elif self.request == 'requests':
self.__http = requests.Session()
if self.using_proxy():
self.__http.proxies = urllib.request.getproxies()
elif self.request == 'requests-futures':
self.__http = FuturesSession()
if self.using_proxy():
self.__http.proxies = urllib.request.getproxies()
elif self.request == 'httplib2':
self.__http = httplib2.Http()
else:
if self.scheme == 'http':
self.__http = http_client.HTTPConnection(self.host, self.port)
elif self.scheme == 'https':
self.__http = http_client.HTTPSConnection(self.host, self.port)
if self.using_proxy():
self.__http.set_tunnel(self.realhost, self.realport, self.proxy_headers)
示例11: open
# 需要導入模塊: from six.moves import http_client [as 別名]
# 或者: from six.moves.http_client import HTTPConnection [as 別名]
def open(self):
if self.scheme == 'http':
self.__http = http_client.HTTPConnection(self.host, self.port)
elif self.scheme == 'https':
self.__http = http_client.HTTPSConnection(self.host, self.port)
if self.using_proxy():
self.__http.set_tunnel(self.realhost, self.realport,
{"Proxy-Authorization": self.proxy_auth})
示例12: main
# 需要導入模塊: from six.moves import http_client [as 別名]
# 或者: from six.moves.http_client import HTTPConnection [as 別名]
def main(unused_argv=None):
target = FLAGS.target
logdir = FLAGS.logdir
if not target or not logdir:
PrintAndLog('Both --target and --logdir are required.', tf.logging.ERROR)
return -1
if os.path.exists(target):
if FLAGS.overwrite:
if os.path.isdir(target):
shutil.rmtree(target)
else:
os.remove(target)
else:
PrintAndLog('Refusing to overwrite target %s without --overwrite' %
target, tf.logging.ERROR)
return -2
path_to_run = server.ParseEventFilesSpec(FLAGS.logdir)
PrintAndLog('About to load Multiplexer. This may take some time.')
multiplexer = event_multiplexer.EventMultiplexer(
size_guidance=server.TENSORBOARD_SIZE_GUIDANCE,
purge_orphaned_data=FLAGS.purge_orphaned_data)
server.ReloadMultiplexer(multiplexer, path_to_run)
PrintAndLog('Multiplexer load finished. Starting TensorBoard server.')
s = server.BuildServer(multiplexer, 'localhost', 0, logdir)
server_thread = threading.Thread(target=s.serve_forever)
server_thread.daemon = True
server_thread.start()
connection = http_client.HTTPConnection('localhost', s.server_address[1])
PrintAndLog('Server setup! Downloading data from the server.')
x = TensorBoardStaticSerializer(connection, target)
x.Run()
PrintAndLog('Done downloading data.')
connection.close()
s.shutdown()
s.server_close()
示例13: setUp
# 需要導入模塊: from six.moves import http_client [as 別名]
# 或者: from six.moves.http_client import HTTPConnection [as 別名]
def setUp(self):
temp_dir = self._GenerateTestData()
self._multiplexer = event_multiplexer.EventMultiplexer(
size_guidance=server.TENSORBOARD_SIZE_GUIDANCE)
server.ReloadMultiplexer(self._multiplexer, {temp_dir: None})
# 0 to pick an unused port.
self._server = server.BuildServer(
self._multiplexer, 'localhost', 0, '/foo/logdir/argument')
self._server_thread = threading.Thread(target=self._server.serve_forever)
self._server_thread.daemon = True
self._server_thread.start()
self._connection = http_client.HTTPConnection(
'localhost', self._server.server_address[1])
示例14: testApplicationPaths_getCached
# 需要導入模塊: from six.moves import http_client [as 別名]
# 或者: from six.moves.http_client import HTTPConnection [as 別名]
def testApplicationPaths_getCached(self):
"""Test the format of the /data/runs endpoint."""
for path in ('/',): # TODO(jart): '/app.js' in open source
connection = http_client.HTTPConnection(
'localhost', self._server.server_address[1])
connection.request('GET', path)
response = connection.getresponse()
self.assertEqual(response.status, 200, msg=path)
self.assertEqual(response.getheader('Cache-Control'),
'private, max-age=3600', msg=path)
connection.close()
示例15: _get_conn
# 需要導入模塊: from six.moves import http_client [as 別名]
# 或者: from six.moves.http_client import HTTPConnection [as 別名]
def _get_conn(self):
if not self.connected:
return None
if self._conn is not None:
return self._conn
host, port = self.master.split(':', 2)
port = int(port)
self._conn = HTTPConnection(host, port, timeout=self._timeout)
return self._conn