requests.exceptions.HTTPError

Here are the examples of the python api requests.exceptions.HTTPError taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: YCM_WIN_X86
Source File: test_requests.py
View license
    def test_http_error(self):
        error = requests.exceptions.HTTPError()
        assert not error.response
        response = requests.Response()
        error = requests.exceptions.HTTPError(response=response)
        assert error.response == response
        error = requests.exceptions.HTTPError('message', response=response)
        assert str(error) == 'message'
        assert error.response == response

Example 2

Project: vdirsyncer
Source File: test_caldav.py
View license
    def test_doesnt_accept_vcard(self, item_type, get_storage_args):
        s = self.storage_class(item_types=(item_type,), **get_storage_args())

        try:
            s.upload(format_item(VCARD_TEMPLATE))
        except (exceptions.Error, requests.exceptions.HTTPError):
            pass
        assert not list(s.list())

Example 3

Project: vdirsyncer
Source File: test_caldav.py
View license
    def test_doesnt_accept_vcard(self, item_type, get_storage_args):
        s = self.storage_class(item_types=(item_type,), **get_storage_args())

        try:
            s.upload(format_item(VCARD_TEMPLATE))
        except (exceptions.Error, requests.exceptions.HTTPError):
            pass
        assert not list(s.list())

Example 4

Project: vdirsyncer
Source File: __init__.py
View license
    def test_dav_broken_item(self, s):
        item = Item(u'HAHA:YES')
        try:
            s.upload(item)
        except (exceptions.Error, requests.exceptions.HTTPError):
            pass
        assert not list(s.list())

Example 5

Project: vdirsyncer
Source File: __init__.py
View license
    def test_dav_broken_item(self, s):
        item = Item(u'HAHA:YES')
        try:
            s.upload(item)
        except (exceptions.Error, requests.exceptions.HTTPError):
            pass
        assert not list(s.list())

Example 6

Project: plotly.py
Source File: test_grid.py
View license
@attr('slow')
@raises(requests.exceptions.HTTPError)
def test_column_append_of_non_uploaded_grid():
    c1 = Column([1, 2, 3, 4], 'first column')
    c2 = Column(['a', 'b', 'c', 'd'], 'second column')
    g = Grid([c1])
    py.grid_ops.append_columns([c2], grid=g)

Example 7

Project: plotly.py
Source File: test_grid.py
View license
@attr('slow')
@raises(requests.exceptions.HTTPError)
def test_row_append_of_non_uploaded_grid():
    c1 = Column([1, 2, 3, 4], 'first column')
    rows = [[1], [2]]
    g = Grid([c1])
    py.grid_ops.append_rows(rows, grid=g)

Example 8

View license
    def test_slideshare_net_parser(self):
        parser = EmbeddableExtractor('slideshare', 'http://www.slideshare.net/earnestagency/the-yes-factor')
        self.assertEqual(parser.get_summary(),
                         '<iframe src="http://www.slideshare.net/slideshow/embed_code/40684167" width="427" height="356" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" style="border:1px solid #CCC; border-width:1px; margin-bottom:5px; max-width: 100%;" allowfullscreen> </iframe> <div style="margin-bottom:5px"> <strong> <a href="https://www.slideshare.net/earnestagency/the-yes-factor" title="The YES Factor: How to persuade business buyers to say yes." target="_blank">The YES Factor: How to persuade business buyers to say yes.</a> </strong> from <strong><a href="http://www.slideshare.net/earnestagency" target="_blank">Earnest</a></strong> </div>\n\n')

        self.assertRaises(requests.exceptions.HTTPError, EmbeddableExtractor, 'slideshare', 'http://www.slideshare.net/whatever404040404')

Example 9

Project: django-konfera
Source File: utils.py
View license
def _get_last_payments():
    """ Get list of payments for last three days from FioBank """
    client = FioBank(token=settings.FIO_BANK_TOKEN)

    today = timezone.now()
    date_from = (today - timedelta(days=3)).strftime(DATE_FORMAT)
    date_to = today.strftime(DATE_FORMAT)

    try:
        data = list(client.period(date_from, date_to))
    except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError) as e:
        logger.error('{} in _get_last_payments'.format(e))
        data = []

    return data

Example 10

Project: djangopackages
Source File: bitbucket.py
View license
    def _get_bitbucket_commits(self, package):
        repo_name = package.repo_name()
        if repo_name.endswith("/"):
            repo_name = repo_name[0:-1]
        target = "%s/%s/changesets/?limit=50" % (API_TARGET, repo_name)
        try:
            data = self.get_json(target)
        except requests.exceptions.HTTPError:
            return []
        if data is None:
            return []  # todo: log this?

        return data.get("changesets", [])

Example 11

Project: rpc-openstack
Source File: elasticsearch.py
View license
def get_json(url, data):
    """Wrap calls to requests to handle exceptions."""
    exceptions = (requests.exceptions.HTTPError,
                  requests.exceptions.ConnectionError)
    try:
        r = requests.get(url, data=data)
    except exceptions as e:
        status_err(str(e))

    return r.json()

Example 12

Project: nailgun
Source File: test_entity_mixins.py
View license
    def test_delete_v1(self):
        """What happens if the server returns an error HTTP status code?"""
        response = mock.Mock()
        response.raise_for_status.side_effect = HTTPError('oh no!')
        with mock.patch.object(
            entity_mixins.EntityDeleteMixin,
            'delete_raw',
            return_value=response,
        ):
            with self.assertRaises(HTTPError):
                self.entity.delete()

Example 13

Project: scalyr-agent-2
Source File: client.py
View license
    def _raise_for_status(self, response, explanation=None):
        """Raises stored :class:`APIError`, if one occurred."""
        try:
            response.raise_for_status()
        except requests.exceptions.HTTPError as e:
            if e.response.status_code == 404:
                raise errors.NotFound(e, response, explanation=explanation)
            raise errors.APIError(e, response, explanation=explanation)

Example 14

Project: scalyr-agent-2
Source File: client.py
View license
    def _raise_for_status(self, response, explanation=None):
        """Raises stored :class:`APIError`, if one occurred."""
        try:
            response.raise_for_status()
        except requests.exceptions.HTTPError as e:
            if e.response.status_code == 404:
                raise errors.NotFound(e, response, explanation=explanation)
            raise errors.APIError(e, response, explanation=explanation)

Example 15

Project: python-hubstorage
Source File: jobq.py
View license
    def push(self, spider, **jobparams):
        jobparams['spider'] = spider
        try:
            for o in self.apipost('push', jl=jobparams):
                if 'error' in o:
                    if 'Active job' in o['error']:
                        raise DuplicateJobError(o['error'])
                    raise HTTPError(o['error'])
                return o
        except HTTPError as exc:
            if exc.response and exc.response.status_code == 409:
                raise DuplicateJobError()
            raise

Example 16

Project: python-scrapinghub
Source File: jobq.py
View license
    def push(self, spider, **jobparams):
        jobparams['spider'] = spider
        try:
            for o in self.apipost('push', jl=jobparams):
                if 'error' in o:
                    if 'Active job' in o['error']:
                        raise DuplicateJobError(o['error'])
                    raise HTTPError(o['error'])
                return o
        except HTTPError as exc:
            if exc.response and exc.response.status_code == 409:
                raise DuplicateJobError()
            raise

Example 17

Project: amy
Source File: api.py
View license
    def __iter__(self):
        try:
            r = self.get(self.endpoint)
            r.raise_for_status()
            pydata_objs = r.json()
        except (requests.exceptions.HTTPError, JSONDecodeError) as e:
            raise IOError('Cannot fetch instances from API: {}'.format(str(e)))
        for obj in pydata_objs:
            yield self.parse(obj)

Example 18

Project: amy
Source File: api.py
View license
    def __contains__(self, pk):
        try:
            self.get(self.endpoint + str(pk)).raise_for_status()
        except requests.exceptions.HTTPError:
            return False
        else:
            return True

Example 19

Project: puppetboard
Source File: test_utils.py
View license
    def test_http_error(self, mock_log):
        err = "NotFound"

        def raise_http_error():
            x = Response()
            x.status_code = 404
            x.reason = err
            raise HTTPError(err, response=x)

        with self.assertRaises(NotFound) as error:
            utils.get_or_abort(raise_http_error)
            mock_log.error.assert_called_with(err)

Example 20

Project: hyperledger-py
Source File: client.py
View license
    def _raise_for_status(self, response, explanation=None):
        """Raises stored :class:`APIError`, if one occurred."""
        try:
            response.raise_for_status()
        except requests.exceptions.HTTPError as e:
            if e.response.status_code == 404:
                raise errors.NotFound(e, response, explanation=explanation)
            raise errors.APIError(e, response, explanation=explanation)

Example 21

Project: hyperledger-py
Source File: client.py
View license
    def _raise_for_status(self, response, explanation=None):
        """Raises stored :class:`APIError`, if one occurred."""
        try:
            response.raise_for_status()
        except requests.exceptions.HTTPError as e:
            if e.response.status_code == 404:
                raise errors.NotFound(e, response, explanation=explanation)
            raise errors.APIError(e, response, explanation=explanation)

Example 22

Project: paasta
Source File: environment.py
View license
def _clean_up_paasta_native_frameworks(context):
    clear_mesos_tools_cache()
    # context.etc_paasta signals that we actually have configured the mesos-cli.json; without this, we don't know where
    # to connect to clean up paasta native frameworks.
    if hasattr(context, 'etc_paasta'):
        for framework in mesos_tools.get_mesos_master().frameworks(active_only=True):
            if framework.name.startswith('paasta '):
                print "cleaning up framework %s" % framework.name
                try:
                    mesos_tools.terminate_framework(framework.id)
                except requests.exceptions.HTTPError as e:
                    print "Got exception when terminating framework %s: %s" % (framework.id, e)

Example 23

Project: paasta
Source File: mesos_maintenance.py
View license
def schedule():
    """Get the Mesos maintenance schedule. This contains hostname/ip mappings and their maintenance window.
    :returns: None
    """
    try:
        schedule = get_maintenance_schedule()
    except HTTPError:
        raise HTTPError("Error getting maintenance schedule.")
    return schedule.text

Example 24

Project: paasta
Source File: mesos_maintenance.py
View license
def get_hosts_with_state(state):
    """Helper function to check the maintenance status and return all hosts
    listed as being in a current state

    :param state: State we are interested in ('down_machines' or 'draining_machines')
    :returns: A list of hostnames in the specified state or an empty list if no machines
    """
    try:
        status = get_maintenance_status().json()
    except HTTPError:
        raise HTTPError("Error getting maintenance status.")
    if not status or state not in status:
        return []
    if 'id' in status[state][0]:
        return [machine['id']['hostname'] for machine in status[state]]
    else:
        return [machine['hostname'] for machine in status[state]]

Example 25

Project: paasta
Source File: mesos_maintenance.py
View license
def reserve(slave_id, resources):
    """Dynamically reserve resources in marathon to prevent tasks from using them.
    :param slave_id: the id of the mesos slave
    :param resources: list of Resource named tuples specifying the name and amount of the resource to (un)reserve
    :returns: boolean where 0 represents success and 1 is a failure
    """
    log.info("Dynamically reserving resoures on %s: %s" % (slave_id, resources))
    payload = {
        'slaveId': slave_id,
        'resources': str(build_reservation_payload(resources)).replace("'", '"').replace('+', '%20')
    }
    client_fn = reserve_api()
    try:
        reserve_output = client_fn(method="POST", endpoint="", data=payload).text
    except HTTPError:
        raise HTTPError("Error adding dynamic reservation.")
    return reserve_output

Example 26

Project: paasta
Source File: mesos_maintenance.py
View license
def unreserve(slave_id, resources):
    """Dynamically unreserve resources in marathon to allow tasks to using them.
    :param slave_id: the id of the mesos slave
    :param resources: list of Resource named tuples specifying the name and amount of the resource to (un)reserve
    :returns: boolean where 0 represents success and 1 is a failure
    """
    log.info("Dynamically unreserving resoures on %s: %s" % (slave_id, resources))
    payload = {
        'slaveId': slave_id,
        'resources': str(build_reservation_payload(resources)).replace("'", '"').replace('+', '%20')
    }
    client_fn = unreserve_api()
    try:
        unreserve_output = client_fn(method="POST", endpoint="", data=payload).text
    except HTTPError:
        raise HTTPError("Error adding dynamic unreservation.")
    return unreserve_output

Example 27

View license
    def test_invalid_key(self):
        self.api_key = 'not a real key'

        try:
            forecastio.load_forecast(
                self.api_key, self.lat, self.lng
            )

            self.assertTrue(False)  # the previous line should throw an exception
        except requests.exceptions.HTTPError as e:
            self.assertTrue(str(e).startswith('400 Client Error: Bad Request'))

Example 28

View license
    def test_invalid_param(self):
        self.lat = ''

        try:
            forecastio.load_forecast(
                self.api_key, self.lat, self.lng
            )

            self.assertTrue(False)  # the previous line should throw an exception
        except requests.exceptions.HTTPError as e:
            self.assertTrue(str(e).startswith('400 Client Error: Bad Request'))

Example 29

Project: ok-client
Source File: pyrebase.py
View license
def raise_detailed_error(request_object):
    try:
        request_object.raise_for_status()
    except HTTPError as e:
        # raise detailed error message
        raise HTTPError(e, request_object.text)

Example 30

Project: canvas
Source File: api.py
View license
@api('post_photo')
@require_user
def tumblr_post_photo(request, access_token, access_token_secret, blog_hostname, comment_id):
    comment = get_object_or_404(QuestComment, id=comment_id)

    try:
        models.post_photo(request.user, blog_hostname, comment)
    except requests.exceptions.HTTPError as e:
        client.create_from_exception()
        raise ServiceError("Error posting to Tumblr.")

Example 31

Project: wharf
Source File: client.py
View license
    def _raise_for_status(self, response, explanation=None):
        """Raises stored :class:`APIError`, if one occurred."""
        try:
            response.raise_for_status()
        except requests.exceptions.HTTPError as e:
            raise APIError(e, response, explanation=explanation)

Example 32

Project: wharf
Source File: client.py
View license
    def _raise_for_status(self, response, explanation=None):
        """Raises stored :class:`APIError`, if one occurred."""
        try:
            response.raise_for_status()
        except requests.exceptions.HTTPError as e:
            raise APIError(e, response, explanation=explanation)

Example 33

Project: kpm
Source File: kubernetes.py
View license
    def get(self):
        cmd = ['get', self.kind, self.name, '-o', 'json']
        try:
            self.result = json.loads(self._call(cmd))
            return self.result
        except subprocess.CalledProcessError:
            return None
        except (requests.exceptions.HTTPError) as e:
            if e.response.status_code == 404:
                return None
            else:
                raise e

Example 34

Project: kpm
Source File: test_kubernetes.py
View license
def test_get_proxy_500_raise(svc_resource):
    proxy = "http://localhost:8001"
    k = Kubernetes(body=svc_resource['body'], proxy=proxy, endpoint=svc_resource['endpoint'])
    url = "%s/%s/%s" % (proxy, svc_resource['endpoint'][1:-1], svc_resource['name'])
    with requests_mock.mock() as m:
        response = get_response(svc_resource["name"], svc_resource["kind"])
        m.get(url, text=response, status_code=500)
        with pytest.raises(requests.exceptions.HTTPError):
            k.get()

Example 35

Project: dd-agent
Source File: test_rabbitmq.py
View license
    def test__get_data(self):
        with mock.patch('rabbitmq.requests') as r:
            from rabbitmq import RabbitMQ, RabbitMQException  # pylint: disable=import-error
            check = RabbitMQ('rabbitmq', {}, {"instances": [{"rabbitmq_api_url": "http://example.com"}]})
            r.get.side_effect = [requests.exceptions.HTTPError, ValueError]
            self.assertRaises(RabbitMQException, check._get_data, '')
            self.assertRaises(RabbitMQException, check._get_data, '')

Example 36

Project: commcare-hq
Source File: tasks.py
View license
def _raise_for_urllib3_response(response):
    '''
    this mimics the behavior of requests.response.raise_for_status so we can
    treat kissmetrics requests and hubspot requests interchangeably in our retry code
    '''
    if 400 <= response.status < 600:
        raise requests.exceptions.HTTPError(response=response)

Example 37

Project: commcare-hq
Source File: tasks.py
View license
def submit_data_to_hub_and_kiss(submit_json):
    hubspot_dispatch = (batch_track_on_hubspot, "Error submitting periodic analytics data to Hubspot")
    kissmetrics_dispatch = (
        _track_periodic_data_on_kiss, "Error submitting periodic analytics data to Kissmetrics"
    )

    for (dispatcher, error_message) in [hubspot_dispatch, kissmetrics_dispatch]:
        try:
            dispatcher(submit_json)
        except requests.exceptions.HTTPError, e:
            _hubspot_failure_soft_assert(False, e.response.content)
        except Exception, e:
            notify_exception(None, u"{msg}: {exc}".format(msg=error_message, exc=e))

Example 38

Project: docker-py
Source File: client.py
View license
    def _raise_for_status(self, response, explanation=None):
        """Raises stored :class:`APIError`, if one occurred."""
        try:
            response.raise_for_status()
        except requests.exceptions.HTTPError as e:
            if e.response.status_code == 404:
                raise errors.NotFound(e, response, explanation=explanation)
            raise errors.APIError(e, response, explanation=explanation)

Example 39

Project: docker-py
Source File: client.py
View license
    def _raise_for_status(self, response, explanation=None):
        """Raises stored :class:`APIError`, if one occurred."""
        try:
            response.raise_for_status()
        except requests.exceptions.HTTPError as e:
            if e.response.status_code == 404:
                raise errors.NotFound(e, response, explanation=explanation)
            raise errors.APIError(e, response, explanation=explanation)

Example 40

Project: twarc
Source File: twarc.py
View license
    def follower_ids(self, screen_name):
        """
        Returns Twitter user id lists for the specified screen_name's
        followers.
        """
        screen_name = screen_name.lstrip('@')
        url = 'https://api.twitter.com/1.1/followers/ids.json'
        params = {'screen_name': screen_name, 'cursor': -1}
        while params['cursor'] != 0:
            try:
                resp = self.get(url, params=params, allow_404=True)
            except requests.exceptions.HTTPError as e:
                if e.response.status_code == 404:
                    logging.info("no users matching %s", screen_name)
                raise e
            user_ids = resp.json()
            for user_id in user_ids['ids']:
                yield user_id
            params['cursor'] = user_ids['next_cursor']

Example 41

Project: twarc
Source File: twarc.py
View license
    def friend_ids(self, screen_name):
        """
        Returns Twitter user id lists for the specified screen_name's friends
        (following).
        """
        screen_name = screen_name.lstrip('@')
        url = 'https://api.twitter.com/1.1/friends/ids.json'
        params = {'screen_name': screen_name, 'cursor': -1}
        while params['cursor'] != 0:
            try:
                resp = self.get(url, params=params, allow_404=True)
            except requests.exceptions.HTTPError as e:
                if e.response.status_code == 404:
                    logging.info("no users matching %s", screen_name)
                raise e
            user_ids = resp.json()
            for user_id in user_ids['ids']:
                yield user_id
            params['cursor'] = user_ids['next_cursor']

Example 42

Project: drawquest-web
Source File: api.py
View license
@api('post_photo')
@require_user
def tumblr_post_photo(request, access_token, access_token_secret, blog_hostname, comment_id):
    comment = get_object_or_404(QuestComment, id=comment_id)

    try:
        models.post_photo(request.user, blog_hostname, comment)
    except requests.exceptions.HTTPError as e:
        client.captureException()
        raise ServiceError("Error posting to Tumblr.")

Example 43

Project: changemonger
Source File: helpers.py
View license
def get_node_or_404(id, version = None):
    try:
        r = changemonger.node(id, version)
        return r
    except requests.exceptions.HTTPError, msg:
        abort(401, "Error retrieving node %s: %s" % (str(id), msg))

Example 44

Project: catsnap
Source File: test_image_truck.py
View license
    @raises(requests.exceptions.HTTPError)
    @patch('catsnap.image_truck.requests')
    def test_new_from_url__raises_on_non_200(self, mock_requests):
        response = Mock()
        response.raise_for_status.side_effect = requests.exceptions.HTTPError
        mock_requests.get.return_value = response

        ImageTruck.new_from_url('http://some.url')

Example 45

Project: f5-common-python
Source File: conftest.py
View license
@pytest.fixture
def raise_custom_HTTPError():
    '''return a function that raises a customized HTTPError when called'''
    def customize_error(status_code, response_txt=''):
        def raise_error(*args, **kwargs):
            mock_response = mock.MagicMock()
            mock_response.status_code = status_code
            mock_response.text = response_txt
            HTTPErrorInstance = HTTPError(response=mock_response)
            raise HTTPErrorInstance
        return raise_error
    return customize_error

Example 46

Project: responses
Source File: test_responses.py
View license
def test_throw_connection_error_explicit():
    @responses.activate
    def run():
        url = 'http://example.com'
        exception = HTTPError('HTTP Error')
        responses.add(
            responses.GET, url, exception)

        with pytest.raises(HTTPError) as HE:
            requests.get(url)

        assert str(HE.value) == 'HTTP Error'

    run()
    assert_reset()

Example 47

Project: python-docs-samples
Source File: main_test.py
View license
@responses.activate
def test_send_error(app):
    responses.add(
        responses.POST,
        'https://api.mailgun.net/v3/example.com/messages',
        body='Test error',
        status=500)

    with pytest.raises(requests.exceptions.HTTPError):
        app.post('/send/email', data={
            'recipient': '[email protected]',
            'submit': 'Send simple email'})

Example 48

Project: perceval
Source File: redmine.py
View license
    def __get_or_fetch_user(self, user_id):
        if user_id in self._users:
            return self._users[user_id]

        logger.debug("User %s not found on client cache; fetching it", user_id)

        try:
            user = self.__fetch_and_parse_user(user_id)
        except requests.exceptions.HTTPError as e:
            if e.response.status_code == 404:
                logger.warning("User %s not found on the server; skipping it",
                               user_id)
                user = {}
            else:
                raise e

        self._users[user_id] = user

        return user

Example 49

Project: heroku.py
Source File: api.py
View license
    def _http_resource(self, method, resource, params=None, data=None):
        """Makes an HTTP request."""

        if not is_collection(resource):
            resource = [resource]

        url = self._url_for(*resource)
        r = self._session.request(method, url, params=params, data=data)

        if r.status_code == 422:
            http_error = HTTPError('%s Client Error: %s' %
                                   (r.status_code, r.content.decode("utf-8")))
            http_error.response = r
            raise http_error

        r.raise_for_status()

        return r

Example 50

Project: home-assistant
Source File: bbox.py
View license
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the Bbox sensor."""
    # Create a data fetcher to support all of the configured sensors. Then make
    # the first call to init the data.
    try:
        bbox_data = BboxData()
        bbox_data.update()
    except requests.exceptions.HTTPError as error:
        _LOGGER.error(error)
        return False

    name = config.get(CONF_NAME)

    sensors = []
    for variable in config[CONF_MONITORED_VARIABLES]:
        sensors.append(BboxSensor(bbox_data, variable, name))

    add_devices(sensors)