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


Python exceptions.HTTPError方法代码示例

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


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

示例1: test_network_error_exception_detector

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import HTTPError [as 别名]
def test_network_error_exception_detector(self):
        http_error = HTTPError()
        self.assertTrue(is_network_error(http_error))

        location_value_error = LocationValueError()
        self.assertTrue(is_network_error(location_value_error))

        pool_error = PoolError(None, 'an error')
        self.assertTrue(is_network_error(pool_error))

        exception = Exception()
        self.assertFalse(is_network_error(exception))

        w3_conn_error = Web3ConnectionException()
        self.assertFalse(is_network_error(w3_conn_error))

        setattr(w3_conn_error, 'errno', errno.ECONNABORTED)
        self.assertTrue(is_network_error(w3_conn_error))

        setattr(w3_conn_error, 'errno', errno.EPERM)
        self.assertFalse(is_network_error(w3_conn_error)) 
开发者ID:gnosis,项目名称:django-eth-events,代码行数:23,代码来源:test_utils.py

示例2: commit_repository

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import HTTPError [as 别名]
def commit_repository(self, branch):
        """
        :param branch: branch to be persisted
        Finalize the repository's scanning in bridgecrew's platform.
        """
        request = None
        try:
            request = http.request("PUT", f"{self.integrations_api_url}",
                                   body=json.dumps({"path": self.repo_path, "branch": branch}),
                                   headers={"Authorization": self.bc_api_key, "Content-Type": "application/json"})
            response = json.loads(request.data.decode("utf8"))
        except HTTPError as e:
            logging.error(f"Failed to commit repository {self.repo_path}\n{e}")
            raise e
        except JSONDecodeError as e:
            logging.error(f"Response of {self.integrations_api_url} is not a valid JSON\n{e}")
            raise e
        finally:
            if request.status == 201 and response["result"] == "Success":
                logging.info(f"Finalize repository {self.repo_id} in bridgecrew's platform")
            else:
                raise Exception(f"Failed to finalize repository {self.repo_id} in bridgecrew's platform\n{response}") 
开发者ID:bridgecrewio,项目名称:checkov,代码行数:24,代码来源:platform_integration.py

示例3: wake_up

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import HTTPError [as 别名]
def wake_up(self):
        """ mod """
        global a_vin
        global a_display_name
        """ end mod """
        """ Request wake up of car. """
        delay = 1
        while True:
            try:
                result = self.vehicle.wake_up()["response"]
                logger.info("wake_up")
                for element in sorted(result):
                    logger.debug("   %s=%s" % (element, result[element]))
                    """ mod """
                    if element == "vin":
                        a_vin = result[element]
                    if element == "display_name":
                        a_display_name = result[element]
                return
            except (KeyError, HTTPError, URLError) as details:
                delay *= 2
                logger.warning("HTTP Error:" + str(details))
                logger.info("Waiting %d seconds before retrying." % delay)
                time.sleep(delay) 
开发者ID:lephisto,项目名称:tesla-apiscraper,代码行数:26,代码来源:apiscraper.py

示例4: whoami

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import HTTPError [as 别名]
def whoami():
    """Show current logged Polyaxon user."""
    try:
        polyaxon_client = PolyaxonClient()
        user = polyaxon_client.users_v1.get_user()
    except ApiException as e:
        if e.status == 403:
            session_expired()
            sys.exit(1)
        handle_cli_error(e, message="Could not get the user info.")
        sys.exit(1)
    except (ApiException, HTTPError) as e:
        handle_cli_error(e, message="Could not load user info.")
        sys.exit(1)

    response = dict_to_tabulate(user.to_dict(), exclude_attrs=["role"])

    Printer.print_header("User info:")
    dict_tabulate(response) 
开发者ID:polyaxon,项目名称:polyaxon,代码行数:21,代码来源:auth.py

示例5: artifacts

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import HTTPError [as 别名]
def artifacts(ctx):
    """Download outputs/artifacts for run.

    Uses /docs/core/cli/#caching

    Examples:

    \b
    $ polyaxon ops -uid=8aac02e3a62a4f0aaa257c59da5eab80 artifacts
    """
    owner, project_name, run_uuid = get_project_run_or_local(
        ctx.obj.get("project"), ctx.obj.get("run_uuid"), is_cli=True,
    )
    try:
        client = RunClient(owner=owner, project=project_name, run_uuid=run_uuid)
        client.download_artifacts()
    except (ApiException, HTTPError) as e:
        handle_cli_error(
            e, message="Could not download outputs for run `{}`.".format(run_uuid)
        )
        sys.exit(1)
    Printer.print_success("Files downloaded.") 
开发者ID:polyaxon,项目名称:polyaxon,代码行数:24,代码来源:operations.py

示例6: _register

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import HTTPError [as 别名]
def _register(self):
        logger.info("Agent is starting.")
        try:
            agent_state = self.get_state()
            if agent_state.status == V1Statuses.STOPPED:
                logger.info(
                    "Agent has been stopped from the platform,"
                    "but the deployment is still running."
                    "Please either set the agent to starting or teardown the agent deployment."
                )
                return
            self.sync()
            self.log_agent_running()
        except (ApiException, HTTPError) as e:
            self.log_agent_failed(
                message="Could not start the agent {}.".format(repr(e))
            )
            sys.exit(1)
        atexit.register(self._wait) 
开发者ID:polyaxon,项目名称:polyaxon,代码行数:21,代码来源:agent.py

示例7: get_json

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import HTTPError [as 别名]
def get_json(self, url):
        try:
            response = self._http_client.request("GET", url, timeout=self.timeout)
            body = response.data
        except HTTPError as e:
            raise GeneralError("Unexpected error %s" % str(e))
        except socket.error as e:
            raise GeneralError("Socket Error: %s" % str(e))

        if response.status != 200:
            raise GeneralError("Server returned unexpected status code - {} - {}".format(response.status,
                                                                                         response.data))
        try:
            result = json.loads(body.decode('utf-8'))
        except Exception as e:
            # Error is parsing json
            raise GeneralError("Error parsing server response (%d) - %s. Got - %s" % (response.status, body, e))

        return result 
开发者ID:Tautulli,项目名称:Tautulli,代码行数:21,代码来源:http_client.py

示例8: is_network_error

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import HTTPError [as 别名]
def is_network_error(exception) -> bool:
    """
    :param exception: an exception error instance
    :return: True if exception detected as a network error, False otherwise
    """
    network_errors = [errno.ECONNABORTED, errno.ECONNREFUSED, errno.ENETRESET, errno.ECONNRESET,
                      errno.ENETUNREACH, errno.ENETDOWN]

    if isinstance(exception, HTTPError) or isinstance(exception, RequestException) or \
            hasattr(exception, 'errno') and exception.errno in network_errors:
        return True

    return False 
开发者ID:gnosis,项目名称:django-eth-events,代码行数:15,代码来源:utils.py

示例9: retry

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import HTTPError [as 别名]
def retry(func):
        def wrapped(*args, **kwargs):
            count = 0
            while True:
                try:
                    return func(*args, **kwargs)
                except (HTTPException, HTTPError, socket.error, socket.timeout):
                    if count >= 10:
                        raise
                    logger.info('Throttling API requests...')
                    time.sleep(2 ** count * 0.5)
                    count += 1
        return wrapped 
开发者ID:zalando,项目名称:spilo,代码行数:15,代码来源:callback_endpoint.py

示例10: dataset_import

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import HTTPError [as 别名]
def dataset_import(
    cache,
    user,
    user_job_id,
    project_id,
    dataset_uri,
    short_name=None,
    extract=False,
    timeout=None,
):
    """Job for dataset import."""
    user = cache.ensure_user(user)
    user_job = cache.get_job(user, user_job_id)
    project = cache.get_project(user, project_id)

    with chdir(project.abs_path):
        try:
            user_job.in_progress()

            import_dataset(
                dataset_uri,
                short_name,
                extract,
                commit_message=f'service: dataset import {dataset_uri}',
                progress=DatasetImportJobProcess(cache, user_job)
            )

            _, remote_branch = repo_sync(
                Repo(project.abs_path), remote='origin'
            )
            user_job.update_extras('remote_branch', remote_branch)

            user_job.complete()
        except (
            HTTPError, ParameterError, DatasetExistsError, GitCommandError
        ) as exp:
            user_job.fail_job(str(exp))

            # Reraise exception, so we see trace in job metadata.
            raise exp 
开发者ID:SwissDataScienceCenter,项目名称:renku-python,代码行数:42,代码来源:datasets.py

示例11: dataset_add_remote_file

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import HTTPError [as 别名]
def dataset_add_remote_file(
    cache, user, user_job_id, project_id, create_dataset, commit_message,
    short_name, url
):
    """Add a remote file to a specified dataset."""
    user = cache.ensure_user(user)
    user_job = cache.get_job(user, user_job_id)
    project = cache.get_project(user, project_id)

    try:
        user_job.in_progress()

        with chdir(project.abs_path):
            urls = url if isinstance(url, list) else [url]
            add_file(
                urls,
                short_name,
                create=create_dataset,
                commit_message=commit_message
            )

            _, remote_branch = repo_sync(
                Repo(project.abs_path), remote='origin'
            )
            user_job.update_extras('remote_branch', remote_branch)

            user_job.complete()
    except (HTTPError, BaseException, GitCommandError) as e:
        user_job.fail_job(str(e)) 
开发者ID:SwissDataScienceCenter,项目名称:renku-python,代码行数:31,代码来源:datasets.py

示例12: retrieve

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import HTTPError [as 别名]
def retrieve(self):
        """Retrieve credential value and its expiry from IAM EC2."""
        # Get role names.
        creds_path = "/latest/meta-data/iam/security-credentials"
        url = self._endpoint + creds_path
        res = self._http_client.urlopen("GET", url)
        if res.status != 200:
            raise HTTPError(
                "request failed with status {0}".format(res.status),
            )
        role_names = res.data.decode("utf-8").split("\n")
        if not role_names:
            raise ResponseError("no role names found in response")

        # Get credentials of first role.
        url = self._endpoint + creds_path + "/" + role_names[0]
        res = self._http_client.urlopen("GET", url)
        if res.status != 200:
            raise HTTPError(
                "request failed with status {0}".format(res.status),
            )
        data = json.loads(res.data)
        if data["Code"] != "Success":
            raise ResponseError(
                "credential retrieval failed with code {0}".format(
                    data["Code"]),
            )

        try:
            expiration = datetime.strptime(data["Expiration"], RFC3339NANO)
        except ValueError:
            expiration = datetime.strptime(data["Expiration"], RFC3339)
        return Value(
            data["AccessKeyId"],
            data["SecretAccessKey"],
            session_token=data["Token"],
        ), expiration + timedelta(minutes=5) 
开发者ID:minio,项目名称:minio-py,代码行数:39,代码来源:providers.py

示例13: test_broken_response

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import HTTPError [as 别名]
def test_broken_response(self):
        request = self.factory.get('/')

        urlopen_mock = MagicMock(side_effect=HTTPError())
        with patch(URLOPEN, urlopen_mock), self.assertRaises(HTTPError):
            CustomProxyView.as_view()(request, path='/') 
开发者ID:danpoland,项目名称:drf-reverse-proxy,代码行数:8,代码来源:test_response.py

示例14: validated_json_payload

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import HTTPError [as 别名]
def validated_json_payload(response):
    """Asserts that the HTTP response was successful and valid JSON."""
    if response.status != 200:
        raise HTTPError(response.status, "non-200 response")

    try:
        data = response.data.decode('utf-8')
        payload = json.loads(data)
    except Exception as e:
        raise Exception("JSON error %s: %s" % (str(e), data[0:1024]))

    return payload 
开发者ID:steemit,项目名称:hivemind,代码行数:14,代码来源:http_client.py

示例15: setup_bridgecrew_credentials

# 需要导入模块: from urllib3 import exceptions [as 别名]
# 或者: from urllib3.exceptions import HTTPError [as 别名]
def setup_bridgecrew_credentials(self, bc_api_key, repo_id):
        """
        Setup credentials against Bridgecrew's platform.
        :param repo_id: Identity string of the scanned repository, of the form <repo_owner>/<repo_name>
        :param bc_api_key: Bridgecrew issued API key
        """
        self.bc_api_key = bc_api_key
        self.repo_id = repo_id
        try:
            request = http.request("POST", self.integrations_api_url, body=json.dumps({"repoId": repo_id}),
                                   headers={"Authorization": bc_api_key, "Content-Type": "application/json"})
            response = json.loads(request.data.decode("utf8"))
            if 'Message' in response:
                if response['Message'] == UNAUTHORIZED_MESSAGE:
                    raise BridgecrewAuthError()
            repo_full_path = response["path"]
            self.bucket, self.repo_path = repo_full_path.split("/", 1)
            self.timestamp = self.repo_path.split("/")[-1]
            self.credentials = response["creds"]
            self.s3_client = boto3.client("s3",
                                          aws_access_key_id=self.credentials["AccessKeyId"],
                                          aws_secret_access_key=self.credentials["SecretAccessKey"],
                                          aws_session_token=self.credentials["SessionToken"],
                                          region_name=DEFAULT_REGION
                                          )
            sleep(10)  # Wait for the policy to update
        except HTTPError as e:
            logging.error(f"Failed to get customer assumed role\n{e}")
            raise e
        except ClientError as e:
            logging.error(f"Failed to initiate client with credentials {self.credentials}\n{e}")
            raise e
        except JSONDecodeError as e:
            logging.error(f"Response of {self.integrations_api_url} is not a valid JSON\n{e}")
            raise e 
开发者ID:bridgecrewio,项目名称:checkov,代码行数:37,代码来源:platform_integration.py


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