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


Python httplib2.ServerNotFoundError方法代码示例

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


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

示例1: instagram_activate

# 需要导入模块: import httplib2 [as 别名]
# 或者: from httplib2 import ServerNotFoundError [as 别名]
def instagram_activate():
    client_id = app.config['INSTAGRAM_CLIENT_ID']
    client_secret = app.config['INSTAGRAM_SECRET']
    redirect_uri = url_for('instagram_oauthorized', _external=True)
    # app.logger.info(redirect_uri)

    scope = ["basic"]
    api = InstagramAPI(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri)

    try:
        redirect_uri = api.get_authorize_login_url(scope=scope)
    except ServerNotFoundError as e:
        flash(f"There was a problem connecting to Instagram. Please try again")
        return redirect(url_for('index'))
    else:
        return redirect(redirect_uri) 
开发者ID:foozmeat,项目名称:moa,代码行数:18,代码来源:app.py

示例2: _IsGCE

# 需要导入模块: import httplib2 [as 别名]
# 或者: from httplib2 import ServerNotFoundError [as 别名]
def _IsGCE():
  """Returns True if running on a GCE instance, otherwise False."""
  try:
    http = httplib2.Http()
    response, _ = http.request(METADATA_SERVER)
    return response.status == 200

  except (httplib2.ServerNotFoundError, socket.error):
    # We might see something like "No route to host" propagated as a socket
    # error. We might also catch transient socket errors, but at that point
    # we're going to fail anyway, just with a different error message. With
    # this approach, we'll avoid having to enumerate all possible non-transient
    # socket errors.
    return False
  except Exception as e:  # pylint: disable=broad-except
    LOG.warning("Failed to determine whether we're running on GCE, so we'll"
                "assume that we aren't: %s", e)
    return False

  return False 
开发者ID:GoogleCloudPlatform,项目名称:gcs-oauth2-boto-plugin,代码行数:22,代码来源:oauth2_client.py

示例3: testGetUnknownServer

# 需要导入模块: import httplib2 [as 别名]
# 或者: from httplib2 import ServerNotFoundError [as 别名]
def testGetUnknownServer(self):
        self.http.force_exception_to_status_code = False
        try:
            self.http.request("http://fred.bitworking.org/")
            self.fail(
                'An httplib2.ServerNotFoundError Exception must be thrown on '
                'an unresolvable server.')
        except httplib2.ServerNotFoundError:
            pass

        # Now test with exceptions turned off
        self.http.force_exception_to_status_code = True

        (response, content) = self.http.request("http://fred.bitworking.org/")
        self.assertEqual(response['content-type'], 'text/plain')
        self.assertTrue(content.startswith(b"Unable to find"))
        self.assertEqual(response.status, 400) 
开发者ID:GoogleCloudPlatform,项目名称:httplib2shim,代码行数:19,代码来源:httplib2_test.py

示例4: listRootFolders

# 需要导入模块: import httplib2 [as 别名]
# 或者: from httplib2 import ServerNotFoundError [as 别名]
def listRootFolders():
    try:
        drive = getDrive(Gdrive.Instance().drive)
        folder = "'root' in parents and mimeType = 'application/vnd.google-apps.folder' and trashed = false"
        fileList = drive.ListFile({'q': folder}).GetList()
    except ServerNotFoundError as e:
        log.info("GDrive Error %s" % e)
        fileList = []
    return fileList 
开发者ID:janeczku,项目名称:calibre-web,代码行数:11,代码来源:gdriveutils.py

示例5: wait_stack_deleted

# 需要导入模块: import httplib2 [as 别名]
# 或者: from httplib2 import ServerNotFoundError [as 别名]
def wait_stack_deleted(self, delay=15):
        stack = True
        while stack:
            try:
                stack = self.get_by_name(self._dm, self.name)
            except (ConnectionResetError, ServerNotFoundError):
                logging.warning('Connection problem')
                continue

            sleep(delay) 
开发者ID:apls777,项目名称:spotty,代码行数:12,代码来源:stack.py

示例6: wait_stack_done

# 需要导入模块: import httplib2 [as 别名]
# 或者: from httplib2 import ServerNotFoundError [as 别名]
def wait_stack_done(self, delay=5):
        is_done = False
        while not is_done:
            try:
                stack = self.get_by_name(self._dm, self.name)
                is_done = stack.is_done
            except (ConnectionResetError, ServerNotFoundError):
                logging.warning('Connection problem')
                continue

            sleep(delay) 
开发者ID:apls777,项目名称:spotty,代码行数:13,代码来源:stack.py

示例7: _send_request

# 需要导入模块: import httplib2 [as 别名]
# 或者: from httplib2 import ServerNotFoundError [as 别名]
def _send_request(self, data, uri):
        """Send requests for the equipment"""
        try:
            count = 0
            while count < self.MAX_RETRIES:
                resp, content = self.HTTP.request(uri,
                                                  method="POST",
                                                  headers=self.HEADERS,
                                                  body=dumps(data))
                if resp.status == status.HTTP_200_OK:
                    return content
                count += 1
                if count >= self.MAX_RETRIES:
                    raise MaxRetryAchieved(self.equipment.nome)
        except MaxRetryAchieved as error:
            log.error(error)
            raise error
        except socket.error as error:
            log.error('Error in socket connection: %s' % error)
            raise error
        except httplib2.ServerNotFoundError as error:
            log.error(
                'Error: %s. Check if the restserver is enabled in %s' %
                (error, self.equipment.nome))
            raise error
        except Exception as error:
            log.error('Error: %s' % error)
            raise error 
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:30,代码来源:plugin.py

示例8: refresh_cache

# 需要导入模块: import httplib2 [as 别名]
# 或者: from httplib2 import ServerNotFoundError [as 别名]
def refresh_cache(labels=None):
    labels = labels if labels is not None else config.SYSTEM_LABELS.keys()
    flow = flow_from_clientsecrets(
        config.CLIENT_SECRET_FILE, scope=config.OAUTH_SCOPE)
    http = httplib2.Http()

    try:
        credentials = OAuth2Credentials.from_json(
            WF.get_password('gmail_credentials'))
        if credentials is None or credentials.invalid:
            credentials = run_flow(flow, PseudoStorage(), http=http)
            WF.save_password('gmail_credentials', credentials.to_json())
            WF.logger.debug('Credentials securely updated')

        http = credentials.authorize(http)
        gmail_service = build('gmail', 'v1', http=http)

        for label in labels:
            WF.cache_data('gmail_%s' %
                          label.lower(), get_list(http, gmail_service, label))
            sleep(2)
        if not WF.cached_data_fresh('gmail_labels', max_age=300):
            WF.cache_data('gmail_labels', get_labels(gmail_service))

    except PasswordNotFound:
        WF.logger.debug('Credentials not found')
        credentials = run_flow(flow, PseudoStorage(), http=http)
        WF.save_password('gmail_credentials', credentials.to_json())
        WF.logger.debug('New Credentials securely saved')

    except httplib2.ServerNotFoundError:
        WF.logger.debug('ServerNotFoundError') 
开发者ID:fniephaus,项目名称:alfred-gmail,代码行数:34,代码来源:gmail_refresh.py

示例9: test_googleapiclient_connection_error

# 需要导入模块: import httplib2 [as 别名]
# 或者: from httplib2 import ServerNotFoundError [as 别名]
def test_googleapiclient_connection_error(self):
        error = httplib2.ServerNotFoundError('Test error')
        firebase_error = _utils.handle_googleapiclient_error(error)
        assert isinstance(firebase_error, exceptions.UnavailableError)
        assert str(firebase_error) == 'Failed to establish a connection: Test error'
        assert firebase_error.cause is error
        assert firebase_error.http_response is None 
开发者ID:firebase,项目名称:firebase-admin-python,代码行数:9,代码来源:test_exceptions.py

示例10: main

# 需要导入模块: import httplib2 [as 别名]
# 或者: from httplib2 import ServerNotFoundError [as 别名]
def main():
    flags = parse_cmdline()
    logger = configure_logs(flags.logfile)
    pageTokenFile = PageTokenFile(flags.ptokenfile)
    for i in range(RETRY_NUM):
        try:
            service = build_service(flags)
            pageToken = pageTokenFile.get()
            deletionList, pageTokenBefore, pageTokenAfter = \
                get_deletion_list(service, pageToken, flags)
            pageTokenFile.save(pageTokenBefore)
            listEmpty = delete_old_files(service, deletionList, flags)
        except client.HttpAccessTokenRefreshError:
            print('Authentication error')
        except httplib2.ServerNotFoundError as e:
            print('Error:', e)
        except TimeoutError:
            print('Timeout: Google backend error.')
            print('Retries unsuccessful. Abort action.')
            return
        else:
            break
        time.sleep(RETRY_INTERVAL)
    else:
        print("Retries unsuccessful. Abort action.")
        return
    
    if listEmpty:
        pageTokenFile.save(pageTokenAfter) 
开发者ID:cfbao,项目名称:google-drive-trash-cleaner,代码行数:31,代码来源:cleaner.py

示例11: testDefaultExceptionHandler

# 需要导入模块: import httplib2 [as 别名]
# 或者: from httplib2 import ServerNotFoundError [as 别名]
def testDefaultExceptionHandler(self):
        """Ensures exception handles swallows (retries)"""
        mock_http_content = 'content'.encode('utf8')
        for exception_arg in (
                http_client.BadStatusLine('line'),
                http_client.IncompleteRead('partial'),
                http_client.ResponseNotReady(),
                socket.error(),
                socket.gaierror(),
                httplib2.ServerNotFoundError(),
                ValueError(),
                exceptions.RequestError(),
                exceptions.BadStatusCodeError(
                    {'status': 503}, mock_http_content, 'url'),
                exceptions.RetryAfterError(
                    {'status': 429}, mock_http_content, 'url', 0)):

            retry_args = http_wrapper.ExceptionRetryArgs(
                http={'connections': {}}, http_request=_MockHttpRequest(),
                exc=exception_arg, num_retries=0, max_retry_wait=0,
                total_wait_sec=0)

            # Disable time.sleep for this handler as it is called with
            # a minimum value of 1 second.
            with patch('time.sleep', return_value=None):
                http_wrapper.HandleExceptionsAndRebuildHttpConnections(
                    retry_args) 
开发者ID:google,项目名称:apitools,代码行数:29,代码来源:http_wrapper_test.py

示例12: _init_google_client

# 需要导入模块: import httplib2 [as 别名]
# 或者: from httplib2 import ServerNotFoundError [as 别名]
def _init_google_client(self):
        start_time = time.monotonic()
        delay = 2
        while True:
            try:
                # sometimes fails: httplib2.ServerNotFoundError: Unable to find the server at www.googleapis.com
                return build("storage", "v1", credentials=self.google_creds)
            except (httplib2.ServerNotFoundError, socket.timeout):
                if time.monotonic() - start_time > 600:
                    raise

            # retry on DNS issues
            time.sleep(delay)
            delay = delay * 2 
开发者ID:aiven,项目名称:pghoard,代码行数:16,代码来源:google.py

示例13: testIsGCEServerNotFound

# 需要导入模块: import httplib2 [as 别名]
# 或者: from httplib2 import ServerNotFoundError [as 别名]
def testIsGCEServerNotFound(self):
    self.mock_http.request.side_effect = httplib2.ServerNotFoundError()

    self.assertFalse(oauth2_client._IsGCE())
    self.mock_http.request.assert_called_once_with(
        oauth2_client.METADATA_SERVER) 
开发者ID:GoogleCloudPlatform,项目名称:gcs-oauth2-boto-plugin,代码行数:8,代码来源:test_oauth2_client.py

示例14: _map_exception

# 需要导入模块: import httplib2 [as 别名]
# 或者: from httplib2 import ServerNotFoundError [as 别名]
def _map_exception(e):
    """Maps an exception from urlib3 to httplib2."""
    if isinstance(e, urllib3.exceptions.MaxRetryError):
        if not e.reason:
            return e
        e = e.reason
    message = e.args[0] if e.args else ''
    if isinstance(e, urllib3.exceptions.ResponseError):
        if 'too many redirects' in message:
            return httplib2.RedirectLimit(message)
    if isinstance(e, urllib3.exceptions.NewConnectionError):
        if ('Name or service not known' in message or
                'nodename nor servname provided, or not known' in message):
            return httplib2.ServerNotFoundError(
                'Unable to find hostname.')
        if 'Connection refused' in message:
            return socket.error((errno.ECONNREFUSED, 'Connection refused'))
    if isinstance(e, urllib3.exceptions.DecodeError):
        return httplib2.FailedToDecompressContent(
            'Content purported as compressed but not uncompressable.',
            httplib2.Response({'status': 500}), '')
    if isinstance(e, urllib3.exceptions.TimeoutError):
        return socket.timeout('timed out')
    if isinstance(e, urllib3.exceptions.SSLError):
        return ssl.SSLError(*e.args)

    return e 
开发者ID:GoogleCloudPlatform,项目名称:httplib2shim,代码行数:29,代码来源:__init__.py

示例15: testGetViaHttpsKeyCert

# 需要导入模块: import httplib2 [as 别名]
# 或者: from httplib2 import ServerNotFoundError [as 别名]
def testGetViaHttpsKeyCert(self):
        #  At this point I can only test
        #  that the key and cert files are passed in
        #  correctly to httplib. It would be nice to have
        #  a real https endpoint to test against.
        http = httplib2.Http(timeout=2)

        http.add_certificate("akeyfile", "acertfile", "bitworking.org")
        try:
            (response, content) = http.request("https://bitworking.org", "GET")
        except AttributeError:
            self.assertEqual(
                http.connections["https:bitworking.org"].key_file, "akeyfile")
            self.assertEqual(
                http.connections[
                    "https:bitworking.org"].cert_file, "acertfile")
        except IOError:
            # Skip on 3.2
            pass

        try:
            (response, content) = http.request(
                "https://notthere.bitworking.org", "GET")
        except httplib2.ServerNotFoundError:
            self.assertEqual(
                http.connections["https:notthere.bitworking.org"].key_file,
                None)
            self.assertEqual(
                http.connections["https:notthere.bitworking.org"].cert_file,
                None)
        except IOError:
            # Skip on 3.2
            pass 
开发者ID:GoogleCloudPlatform,项目名称:httplib2shim,代码行数:35,代码来源:httplib2_test.py


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