当前位置: 首页>>代码示例>>Python>>正文


Python http_client.HTTPConnection方法代码示例

本文整理汇总了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 
开发者ID:cloudbase,项目名称:cloudbase-init,代码行数:25,代码来源:cloudstack.py

示例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() 
开发者ID:tobegit3hub,项目名称:deep_image_model,代码行数:20,代码来源:server_test.py

示例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() 
开发者ID:douban,项目名称:pymesos,代码行数:21,代码来源:scheduler.py

示例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. 
开发者ID:openstack,项目名称:manila,代码行数:25,代码来源:limits.py

示例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() 
开发者ID:redcanari,项目名称:canari3,代码行数:24,代码来源:runner.py

示例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 
开发者ID:Tautulli,项目名称:Tautulli,代码行数:23,代码来源:test_http.py

示例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 
开发者ID:GoogleCloudPlatform,项目名称:PerfKitBenchmarker,代码行数:21,代码来源:publisher.py

示例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 
开发者ID:lxc,项目名称:pylxd,代码行数:13,代码来源:connection.py

示例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 
开发者ID:MayOneUS,项目名称:pledgeservice,代码行数:16,代码来源:http.py

示例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) 
开发者ID:crash-override404,项目名称:linepy-modified,代码行数:30,代码来源:transport.py

示例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}) 
开发者ID:Aditmadzs,项目名称:Protect4,代码行数:10,代码来源:THttpClient.py

示例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() 
开发者ID:tobegit3hub,项目名称:deep_image_model,代码行数:41,代码来源:serialize_tensorboard.py

示例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]) 
开发者ID:tobegit3hub,项目名称:deep_image_model,代码行数:15,代码来源:server_test.py

示例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() 
开发者ID:tobegit3hub,项目名称:deep_image_model,代码行数:13,代码来源:server_test.py

示例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 
开发者ID:douban,项目名称:pymesos,代码行数:13,代码来源:scheduler.py


注:本文中的six.moves.http_client.HTTPConnection方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。