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


Python exceptions.HTTPError方法代码示例

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


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

示例1: demo

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import HTTPError [as 别名]
def demo():
    constructor = CustodiaSimpleConstructor(
        'http+unix://%2E%2Fserver_socket/secrets'
    )
    constructor.client.headers['REMOTE_USER'] = 'user'

    # create entries
    try:
        c = constructor.client.list_container('test')
    except HTTPError:
        constructor.client.create_container('test')
        c = []
    if 'key' not in c:
        constructor.client.set_secret('test/key', 'secret password')

    yaml.add_constructor(CustodiaSimpleConstructor.yaml_tag,
                         constructor)
    yaml_str = 'password: !custodia/simple test/key'
    print(yaml_str)
    result = yaml.load(yaml_str)
    print(result) 
开发者ID:latchset,项目名称:custodia,代码行数:23,代码来源:yaml_ext.py

示例2: figshare_request

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import HTTPError [as 别名]
def figshare_request(
        endpoint=None, data=None, method='GET', url=None,
        binary=False, error_level=logging.ERROR):
    """Perform a REST request against the figshare API."""
    headers = {'Authorization': 'token ' + repository().get('token', '')}
    if data is not None and not binary:
        data = json.dumps(data)
    response = requests.request(
        method, url or _FIGSHARE_BASE_URL.format(endpoint=endpoint), headers=headers, data=data)
    try:
        response.raise_for_status()
        try:
            data = json.loads(response.content)
        except ValueError:
            data = response.content
    except HTTPError as error:
        logger.log(error_level, error)
        raise error
    return data 
开发者ID:int-brain-lab,项目名称:ibllib,代码行数:21,代码来源:onelight.py

示例3: call_api

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import HTTPError [as 别名]
def call_api(self, path: str, params: dict = None) -> dict:
        if params is None:
            params = {}

        api_url = self.base_url + path

        headers = {
            "Authorization": f"basic {self.token}"
        }

        try:
            response = request("GET", self.base_url + path, params=komand.helper.clean(params), headers=headers)
            response.raise_for_status()
            return komand.helper.clean(response.json())
        except HTTPError as httpError:
            raise PluginException(
                cause=f"Failed to get a valid response from AttackerKB at endpoint {api_url}",
                assistance=f"Response was {httpError.response.text}",
                data=httpError
            ) 
开发者ID:rapid7,项目名称:insightconnect-plugins,代码行数:22,代码来源:api.py

示例4: turn_green_callback

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import HTTPError [as 别名]
def turn_green_callback(self, kwargs):
        """This is needed because the turn_on command can result in a HTTP 503 when homeassistant is restarting"""
        try:
            self.call_service(
                "light/turn_on",
                entity_id=self.light,
                rgb_color=[0, 255, 0],
                white_value=0,
            )
            self.log("Turning {} green".format(self.friendly_name(self.light)))
            self.timer_handle_list.append(self.run_in(self.turn_off_callback, 5))
        except HTTPError as exception:
            self.log(
                "Error trying to turn on entity. Will try again in 1s. Error: {}".format(
                    exception
                ),
                level="WARNING",
            )
            self.timer_handle_list.append(self.run_in(self.turn_green_callback, 1)) 
开发者ID:eifinger,项目名称:appdaemon-scripts,代码行数:21,代码来源:turnOffBarAfterRestart.py

示例5: turn_on_callback

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import HTTPError [as 别名]
def turn_on_callback(self, kwargs):
        """This is needed because the turn_on command can result in a HTTP 503 when homeassistant is restarting"""
        try:
            self.turn_on(kwargs["turn_on_entity"])
        except HTTPError as exception:
            self.log(
                "Error trying to turn on entity. Will try again in 1s. Error: {}".format(
                    exception
                ),
                level="WARNING",
            )
            self.timer_handle_list.append(
                self.run_in(
                    self.turn_on_callback, 1, turn_on_entity=kwargs["turn_on_entity"]
                )
            ) 
开发者ID:eifinger,项目名称:appdaemon-scripts,代码行数:18,代码来源:isUserHomeDeterminer.py

示例6: turn_off_callback

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import HTTPError [as 别名]
def turn_off_callback(self, kwargs):
        """This is needed because the turn_off command can result in a HTTP 503 when homeassistant is restarting"""
        try:
            self.turn_off(kwargs["turn_off_entity"])
        except HTTPError as exception:
            self.log(
                "Error trying to turn off entity. Will try again in 1s. Error: {}".format(
                    exception
                ),
                level="WARNING",
            )
            self.timer_handle_list.append(
                self.run_in(
                    self.turn_off_callback, 1, turn_off_entity=kwargs["turn_off_entity"]
                )
            ) 
开发者ID:eifinger,项目名称:appdaemon-scripts,代码行数:18,代码来源:isUserHomeDeterminer.py

示例7: request

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import HTTPError [as 别名]
def request(self, url, *args, **kwargs):
        try:
            stream = HttpStream(url, *args, verbose=self.verbose, **kwargs)
            if kwargs.get('stream', False):
                return stream

            with stream as s:
                content = s.req.content
                return HttpResponse(s.status_code, s.headers, content)
        # Timeout will catch both ConnectTimout and ReadTimeout
        except (RetryError, Timeout) as ex:
            raise OsbsNetworkException(url, str(ex), '',
                                       cause=ex, traceback=sys.exc_info()[2])
        except HTTPError as ex:
            raise OsbsNetworkException(url, str(ex), ex.response.status_code,
                                       cause=ex, traceback=sys.exc_info()[2])
        except Exception as ex:
            raise OsbsException(cause=ex, traceback=sys.exc_info()[2]) 
开发者ID:containerbuildsystem,项目名称:osbs-client,代码行数:20,代码来源:http.py

示例8: _handle_response

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import HTTPError [as 别名]
def _handle_response(self, response):
        """ Helper method to handle response containing datafile.

        Args:
            response: requests.Response
        """
        try:
            response.raise_for_status()
        except requests_exceptions.HTTPError as err:
            self.logger.error('Fetching datafile from {} failed. Error: {}'.format(self.datafile_url, str(err)))
            return

        # Leave datafile and config unchanged if it has not been modified.
        if response.status_code == http_status_codes.not_modified:
            self.logger.debug('Not updating config as datafile has not updated since {}.'.format(self.last_modified))
            return

        self.set_last_modified(response.headers)
        self._set_config(response.content) 
开发者ID:optimizely,项目名称:python-sdk,代码行数:21,代码来源:config_manager.py

示例9: test_failure

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import HTTPError [as 别名]
def test_failure(self, debugger):
        from requests.exceptions import HTTPError

        with mock.patch("dallinger.deployment.HerokuLocalWrapper"):
            with mock.patch("dallinger.deployment.requests.post") as mock_post:
                mock_post.return_value = mock.Mock(
                    ok=False,
                    json=mock.Mock(return_value={"message": "msg!"}),
                    raise_for_status=mock.Mock(side_effect=HTTPError),
                    status_code=500,
                    text="Failure",
                )
                debugger.run()

        # Only one launch attempt should be made in debug mode
        debugger.out.error.assert_has_calls(
            [
                mock.call("Error accessing http://0.0.0.0:5000/launch (500):\nFailure"),
                mock.call("Experiment launch failed, check web dyno logs for details."),
                mock.call("msg!"),
            ]
        ) 
开发者ID:Dallinger,项目名称:Dallinger,代码行数:24,代码来源:test_deployment.py

示例10: arp_delete

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import HTTPError [as 别名]
def arp_delete(self,
                   bigip,
                   ip_address,
                   partition=const.DEFAULT_PARTITION):
        if ip_address:
            address = urllib.quote(self._remove_route_domain_zero(ip_address))
            arp = bigip.tm.net.arps.arp
            try:
                if arp.exists(name=address, partition=partition):
                    obj = arp.load(name=address, partition=partition)
                    obj.delete()
            except HTTPError as err:
                LOG.error("Error deleting arp %s. "
                          "Repsponse status code: %s. Response "
                          "message: %s." % (address,
                                            err.response.status_code,
                                            err.message))

            return True

        return False 
开发者ID:F5Networks,项目名称:f5-openstack-agent,代码行数:23,代码来源:network_helper.py

示例11: delete_all_fdb_entries

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import HTTPError [as 别名]
def delete_all_fdb_entries(
            self,
            bigip,
            tunnel_name,
            partition=const.DEFAULT_PARTITION):
        """Delete all fdb entries."""
        try:
            t = bigip.tm.net.fdb.tunnels.tunnel
            obj = t.load(name=tunnel_name, partition=partition)
            obj.modify(records=None)
        except HTTPError as err:
            LOG.error("Error deleting all fdb entries %s. "
                      "Repsponse status code: %s. Response "
                      "message: %s." % (tunnel_name,
                                        err.response.status_code,
                                        err.message)) 
开发者ID:F5Networks,项目名称:f5-openstack-agent,代码行数:18,代码来源:network_helper.py

示例12: skip_http_error

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import HTTPError [as 别名]
def skip_http_error(statuses):
    """
    A decorator to wrap with try..except to swallow
    specific HTTP errors.

    @skip_http_error((404, 503))
    def fetch():
        ...
    """

    assert isinstance(statuses, tuple)

    def decorator(func):
        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except HTTPError as e:
                status_code = e.response.status_code
                if status_code in statuses:
                    log.warn(str(e))
                else:
                    raise
        return wrapper
    return decorator 
开发者ID:alpacahq,项目名称:pylivetrader,代码行数:26,代码来源:alpaca.py

示例13: parental_control_data

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import HTTPError [as 别名]
def parental_control_data(self, password):
        # Ask to the service if password is right and get the PIN status
        from requests import exceptions
        profile_guid = g.LOCAL_DB.get_active_profile_guid()
        try:
            response = self._post('profile_hub',
                                  data={'destination': 'contentRestrictions',
                                        'guid': profile_guid,
                                        'password': password,
                                        'task': 'auth'})
            if response.get('status') != 'ok':
                common.warn('Parental control status issue: {}', response)
                raise MissingCredentialsError
        except exceptions.HTTPError as exc:
            if exc.response.status_code == 500:
                # This endpoint raise HTTP error 500 when the password is wrong
                raise MissingCredentialsError
            raise
        # Warning - parental control levels vary by country or region, no fixed values can be used
        # Note: The language of descriptions change in base of the language of selected profile
        response_content = self._get('restrictions', data={'password': password}, append_to_address=profile_guid)
        extracted_content = website.extract_parental_control_data(response_content, response['maturity'])
        response['profileInfo']['profileName'] = website.parse_html(response['profileInfo']['profileName'])
        extracted_content['data'] = response
        return extracted_content 
开发者ID:CastagnaIT,项目名称:plugin.video.netflix,代码行数:27,代码来源:nfsession.py

示例14: test_do_api_call_succeeds_after_retrying

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import HTTPError [as 别名]
def test_do_api_call_succeeds_after_retrying(self):
        for exception in [requests_exceptions.ConnectionError,
                          requests_exceptions.SSLError,
                          requests_exceptions.Timeout,
                          requests_exceptions.ConnectTimeout,
                          requests_exceptions.HTTPError]:
            with mock.patch('airflow.providers.databricks.hooks.databricks.requests') as mock_requests:
                with mock.patch.object(self.hook.log, 'error') as mock_errors:
                    setup_mock_requests(
                        mock_requests,
                        exception,
                        error_count=2,
                        response_content={'run_id': '1'}
                    )

                    response = self.hook._do_api_call(SUBMIT_RUN_ENDPOINT, {})

                    self.assertEqual(mock_errors.call_count, 2)
                    self.assertEqual(response, {'run_id': '1'}) 
开发者ID:apache,项目名称:airflow,代码行数:21,代码来源:test_databricks.py

示例15: test_do_api_call_waits_between_retries

# 需要导入模块: from requests import exceptions [as 别名]
# 或者: from requests.exceptions import HTTPError [as 别名]
def test_do_api_call_waits_between_retries(self, mock_sleep):
        retry_delay = 5
        self.hook = DatabricksHook(retry_delay=retry_delay)

        for exception in [requests_exceptions.ConnectionError,
                          requests_exceptions.SSLError,
                          requests_exceptions.Timeout,
                          requests_exceptions.ConnectTimeout,
                          requests_exceptions.HTTPError]:
            with mock.patch('airflow.providers.databricks.hooks.databricks.requests') as mock_requests:
                with mock.patch.object(self.hook.log, 'error'):
                    mock_sleep.reset_mock()
                    setup_mock_requests(mock_requests, exception)

                    with self.assertRaises(AirflowException):
                        self.hook._do_api_call(SUBMIT_RUN_ENDPOINT, {})

                    self.assertEqual(len(mock_sleep.mock_calls), self.hook.retry_limit - 1)
                    calls = [
                        mock.call(retry_delay),
                        mock.call(retry_delay)
                    ]
                    mock_sleep.assert_has_calls(calls) 
开发者ID:apache,项目名称:airflow,代码行数:25,代码来源:test_databricks.py


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