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


Python httplib.HTTPException方法代码示例

本文整理汇总了Python中httplib.HTTPException方法的典型用法代码示例。如果您正苦于以下问题:Python httplib.HTTPException方法的具体用法?Python httplib.HTTPException怎么用?Python httplib.HTTPException使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在httplib的用法示例。


在下文中一共展示了httplib.HTTPException方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: send

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import HTTPException [as 别名]
def send(verb, endpoint, body):
    __API_LISTENER = __IP_ADDR + ":" + __PORT
    iprint("sending to: " + __API_LISTENER)
    try:
        conn = httplib.HTTPConnection(__API_LISTENER)
        if len(body) != 0:
            conn.request(
                verb,
                endpoint,
                body,
                {"Content-Type": "application/json"}
            )
        else :
            conn.request(verb, endpoint)

        response = conn.getresponse()
        body = response.read()
        return response.status, response.reason, body
    except (httplib.HTTPException, socket.error) as ex:
        print ("Error: %s" % ex)
        quit() 
开发者ID:nanoleaf,项目名称:aurora-sdk-mac,代码行数:23,代码来源:AuroraAPI.py

示例2: do_http_get

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import HTTPException [as 别名]
def do_http_get(self, base_url, get_url):
        """
            Generic http get function
        """
        try:
            connection = httplib.HTTPConnection(base_url)
            connection.request('GET', get_url)
            resp = connection.getresponse()
        except httplib.HTTPException:
            print ("LOGGER: Unable to perform fetch to the"
                   " given url due to HTTPLIB exception",
                   base_url + get_url)
            return (False, None)
        except Exception, exc:
            print ("LOGGER: Unable to perform fetch to the given"
                   " url {0} due to exception {1}"
                   .format(base_url + get_url, exc))
            raise 
开发者ID:linkedin,项目名称:simoorg,代码行数:20,代码来源:test_MoriaiApi.py

示例3: ping

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import HTTPException [as 别名]
def ping():
    """Check if container is listening on the specified port."""
    try:
        host = sys.argv[1]
        port = int(sys.argv[2])
    except (IndexError, ValueError):
        host = '0.0.0.0'
        port = 8080

    con = None
    success = True
    try:
        con = httplib.HTTPConnection(host, port)
        con.connect()
    except (socket.error, httplib.HTTPException):
        success = False
    finally:
        if con:
            con.close()
    if success:
        logging.info('success')
        sys.exit(0)
    logging.info('failure')
    sys.exit(1) 
开发者ID:GoogleCloudPlatform,项目名称:appstart,代码行数:26,代码来源:pinger.py

示例4: _FetchUserListPage

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import HTTPException [as 别名]
def _FetchUserListPage(self, next_page_token=None):
    """Helper that handles exceptions retrieving pages of users.

    Args:
      next_page_token: Used for ongoing paging of users.

    Returns:
      List of users retrieved (one page with default page size: 100 users).
    """
    # 'deleted' users are not examined.
    # https://developers.google.com/admin-sdk/directory/v1/reference/users/list
    request = self._users_collection.list(domain=self._user_domain,
                                          maxResults=_MAX_RESULT_PAGE_SIZE,
                                          query=self._search_query,
                                          pageToken=next_page_token)
    # Not infrequently seeing:
    # 'HTTPException: Deadline exceeded while waiting for HTTP response '
    # 'from URL: https://www.googleapis.com/admin/directory/v1/users'
    # '?query=email%3A6%2A&domain=capgsfishing.com&alt=json&maxResults=500'
    # Default socket timeout seems to be 5s so increasing it to 10s
    # in GetAuthorizedHttp() seems to have helped.
    return request.execute(http=self._http) 
开发者ID:google,项目名称:googleapps-message-recall,代码行数:24,代码来源:user_retriever.py

示例5: GetUserAttributes

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import HTTPException [as 别名]
def GetUserAttributes(self, user_email):
    """Helper to retrieve user attributes from the Admin SDK API.

    Args:
      user_email: String email address of the form user@domain.com.

    Returns:
      Dictionary of user_attributes discovered.

    Raises:
      MessageRecallError: If unable to execute the API call.
    """
    request = self._users_collection.get(userKey=user_email)
    try:
      return request.execute(
          http=credentials_utils.GetAuthorizedHttp(user_email))
    except (HttpError, httplib.HTTPException) as e:
      if e.resp.status == 403:  # If user is not an admin...
        return {}
      raise 
开发者ID:google,项目名称:googleapps-message-recall,代码行数:22,代码来源:user_retriever.py

示例6: get_flows

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import HTTPException [as 别名]
def get_flows(address, dpid):
    assert type(dpid) == int

    flows = []
    try:
        path = '%s%d' % (_FLOW_PATH_BASE, dpid)
        flows = json.loads(_do_request(address, path).read())[str(dpid)]
    except IOError as e:
        LOG.error('REST API(%s) is not available.', address)
        raise
    except httplib.HTTPException as e:
        if e[0].status == httplib.NOT_FOUND:
            pass  # switch already deleted
        else:
            LOG.error('REST API(%s, path=%s) request error.', address, path)
            raise
    return flows 
开发者ID:OpenState-SDN,项目名称:ryu,代码行数:19,代码来源:proxy.py

示例7: _polling_loop

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import HTTPException [as 别名]
def _polling_loop(self):
        LOG.debug('TopologyWatcher: Enter polling loop')
        while self.is_active:
            try:
                switches_json = self.tc.list_switches().read()
                links_json = self.tc.list_links().read()
            except (SocketError, HTTPException) as e:
                LOG.debug('TopologyWatcher: REST API(%s) is not avaliable.' %
                          self.address)
                LOG.debug('        wait %d secs...' %
                          self._REST_RETRY_WAIT)
                self._call_rest_error_handler(e)
                gevent.sleep(self._REST_RETRY_WAIT)
                continue

            if self._is_updated(switches_json, links_json):
                LOG.debug('TopologyWatcher: topology updated')
                new_topo = Topology(switches_json, links_json)
                delta = new_topo - self.topo
                self.topo = new_topo

                self._call_update_handler(delta)

            gevent.sleep(self._LOOP_WAIT) 
开发者ID:OpenState-SDN,项目名称:ryu,代码行数:26,代码来源:topology.py

示例8: _start_transaction

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import HTTPException [as 别名]
def _start_transaction(self, h, req):
        try:
            if req.has_data():
                data = req.data
                if hasattr(req, 'selector'):
                    h.putrequest(req.get_method() or 'POST', req.selector, skip_host=req.has_header("Host"), skip_accept_encoding=req.has_header("Accept-encoding"))
                else:
                    h.putrequest(req.get_method() or 'POST', req.get_selector(), skip_host=req.has_header("Host"), skip_accept_encoding=req.has_header("Accept-encoding"))
                if not req.headers.has_key('Content-type'):
                    h.putheader('Content-type',
                                'application/x-www-form-urlencoded')
                if not req.headers.has_key('Content-length'):
                    h.putheader('Content-length', '%d' % len(data))
            else:
                if hasattr(req, 'selector'):
                    h.putrequest(req.get_method() or 'GET', req.selector, skip_host=req.has_header("Host"), skip_accept_encoding=req.has_header("Accept-encoding"))
                else:
                    h.putrequest(req.get_method() or 'GET', req.get_selector(), skip_host=req.has_header("Host"), skip_accept_encoding=req.has_header("Accept-encoding"))
        except (socket.error, httplib.HTTPException), err:
            raise urllib2.URLError(err) 
开发者ID:sabri-zaki,项目名称:EasY_HaCk,代码行数:22,代码来源:keepalive.py

示例9: handle_one_request

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import HTTPException [as 别名]
def handle_one_request(self):
    """Override. Invoked from BaseHTTPRequestHandler constructor."""
    self.raw_requestline = self.rfile.readline()
    if not self.raw_requestline:
      self.close_connection = 1
      return
    if not self.parse_request():
      return

    process = GlobalProcess()
    balance_set = process.GetBalanceSet()
    request_size = int(self.headers.get('content-length', 0))
    payload = self.rfile.read(request_size)




    for port in balance_set:
      logging.debug('balancer to port %d',  port)
      connection = self.connection_handler(process.host, port=port)


      connection.response_class = ForwardResponse
      connection.request(self.command, self.path, payload, dict(self.headers))
      try:
        response = connection.getresponse()
      except httplib.HTTPException, e:


        self.send_error(httplib.INTERNAL_SERVER_ERROR, str(e))
        return

      if response.status != httplib.SERVICE_UNAVAILABLE:
        self.wfile.write(response.data)
        return 
开发者ID:elsigh,项目名称:browserscope,代码行数:37,代码来源:dev_appserver_multiprocess.py

示例10: _conn_request

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import HTTPException [as 别名]
def _conn_request(self, conn, request_uri, method, body, headers):
        i = 0
        seen_bad_status_line = False
        while i < RETRIES:
            i += 1
            try:
                if hasattr(conn, 'sock') and conn.sock is None:
                    conn.connect()
                conn.request(method, request_uri, body, headers)
            except socket.timeout:
                raise
            except socket.gaierror:
                conn.close()
                raise ServerNotFoundError("Unable to find the server at %s" % conn.host)
            except ssl_SSLError:
                conn.close()
                raise
            except socket.error, e:
                err = 0
                if hasattr(e, 'args'):
                    err = getattr(e, 'args')[0]
                else:
                    err = e.errno
                if err == errno.ECONNREFUSED: # Connection refused
                    raise
            except httplib.HTTPException:
                # Just because the server closed the connection doesn't apparently mean
                # that the server didn't send a response.
                if hasattr(conn, 'sock') and conn.sock is None:
                    if i < RETRIES-1:
                        conn.close()
                        conn.connect()
                        continue
                    else:
                        conn.close()
                        raise
                if i < RETRIES-1:
                    conn.close()
                    conn.connect()
                    continue 
开发者ID:mortcanty,项目名称:earthengine,代码行数:42,代码来源:__init__.py

示例11: __init__

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import HTTPException [as 别名]
def __init__(self, *args, **kw):
        unittest.TestCase.__init__(self, *args, **kw)
        try:
            self.open_mapping_file().close() # test it to report the error early
        except (IOError, HTTPException):
            self.skipTest("Could not retrieve "+self.mapfileurl) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:8,代码来源:multibytecodec_support.py

示例12: test_too_many_headers

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import HTTPException [as 别名]
def test_too_many_headers(self):
        headers = '\r\n'.join('Header%d: foo' % i for i in xrange(200)) + '\r\n'
        text = ('HTTP/1.1 200 OK\r\n' + headers)
        s = FakeSocket(text)
        r = httplib.HTTPResponse(s)
        self.assertRaises(httplib.HTTPException, r.begin) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:8,代码来源:test_httplib.py

示例13: _format_exception

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import HTTPException [as 别名]
def _format_exception(self, exception):
        '''Transform a keystone, nova, neutron  exception into a vimconn exception'''
        if isinstance(exception, (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError,
                                  ConnectionError, ksExceptions.ConnectionError, neExceptions.ConnectionFailed,
                                  neClient.exceptions.ConnectionFailed)):
            raise vimconn.vimconnConnectionException(type(exception).__name__ + ": " + str(exception))            
        elif isinstance(exception, (nvExceptions.ClientException, ksExceptions.ClientException, 
                                    neExceptions.NeutronException, nvExceptions.BadRequest)):
            raise vimconn.vimconnUnexpectedResponse(type(exception).__name__ + ": " + str(exception))
        elif isinstance(exception, (neExceptions.NetworkNotFoundClient, nvExceptions.NotFound)):
            raise vimconn.vimconnNotFoundException(type(exception).__name__ + ": " + str(exception))
        elif isinstance(exception, nvExceptions.Conflict):
            raise vimconn.vimconnConflictException(type(exception).__name__ + ": " + str(exception))
        else: # ()
            raise vimconn.vimconnConnectionException(type(exception).__name__ + ": " + str(exception)) 
开发者ID:nfvlabs,项目名称:openmano,代码行数:17,代码来源:vimconn_openstack.py

示例14: _conn_request

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import HTTPException [as 别名]
def _conn_request(self, conn, request_uri, method, body, headers):
        for i in range(RETRIES):
            try:
                if hasattr(conn, 'sock') and conn.sock is None:
                    conn.connect()
                conn.request(method, request_uri, body, headers)
            except socket.timeout:
                raise
            except socket.gaierror:
                conn.close()
                raise ServerNotFoundError("Unable to find the server at %s" % conn.host)
            except ssl_SSLError:
                conn.close()
                raise
            except socket.error, e:
                err = 0
                if hasattr(e, 'args'):
                    err = getattr(e, 'args')[0]
                else:
                    err = e.errno
                if err == errno.ECONNREFUSED: # Connection refused
                    raise
            except httplib.HTTPException:
                # Just because the server closed the connection doesn't apparently mean
                # that the server didn't send a response.
                if hasattr(conn, 'sock') and conn.sock is None:
                    if i < RETRIES-1:
                        conn.close()
                        conn.connect()
                        continue
                    else:
                        conn.close()
                        raise
                if i < RETRIES-1:
                    conn.close()
                    conn.connect()
                    continue 
开发者ID:Schibum,项目名称:sndlatr,代码行数:39,代码来源:__init__.py

示例15: request

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import HTTPException [as 别名]
def request(self, connection, url, headers, data=None, timeout=0):
		result = response = None
		try:
			if data: connection.request('POST', url, data, headers)
			else: connection.request('GET', url, headers=headers)
			response = self.timeout_response(connection, timeout)
			if not response:
				return None
			if response.status == httplib.UNAUTHORIZED:
				say_line('Wrong username or password for %s', self.server().name)
				self.authorization_failed = True
				raise NotAuthorized()
			r = self.max_redirects
			while response.status == httplib.TEMPORARY_REDIRECT:
				response.read()
				url = response.getheader('Location', '')
				if r == 0 or url == '': raise HTTPException('Too much or bad redirects')
				connection.request('GET', url, headers=headers)
				response = self.timeout_response(connection, timeout)
				r -= 1
			self.long_poll_url = response.getheader('X-Long-Polling', '')
			self.switch.update_time = bool(response.getheader('X-Roll-NTime', ''))
			hostList = response.getheader('X-Host-List', '')
			self.stratum_header = response.getheader('x-stratum', '')
			if (not self.options.nsf) and hostList: self.switch.add_servers(loads(hostList))
			result = loads(response.read())
			if result['error']:
				say_line('server error: %s', result['error']['message'])
				raise RPCError(result['error']['message'])
			return (connection, result)
		finally:
			if not result or not response or (response.version == 10 and response.getheader('connection', '') != 'keep-alive') or response.getheader('connection', '') == 'close':
				connection.close()
				connection = None 
开发者ID:theRealTacoTime,项目名称:poclbm,代码行数:36,代码来源:GetworkSource.py


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