當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。