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.
166 Examples
5
Example 1
Project: YCM_WIN_X86 Source File: test_requests.py
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
3
Example 2
Project: ok-client Source File: pyrebase.py
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)
3
Example 3
Project: perceval Source File: redmine.py
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
3
Example 4
Project: golem Source File: stream.py
@staticmethod
def _assert_transfer_encoding(headers):
value = 'chunked'
transfer_encoding = headers.get('transfer-encoding', None)
if transfer_encoding != value:
raise HTTPError('Invalid transfer encoding: {}'
.format(transfer_encoding))
3
Example 5
Project: catsnap Source File: test_image_truck.py
@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')
3
Example 6
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
3
Example 7
Project: home-assistant Source File: test_darksky.py
@patch('forecastio.api.get_forecast')
def test_setup_bad_api_key(self, mock_get_forecast):
"""Test for handling a bad API key."""
# The Dark Sky API wrapper that we use raises an HTTP error
# when you try to use a bad (or no) API key.
url = 'https://api.darksky.net/forecast/{}/{},{}?units=auto'.format(
self.key, str(self.lat), str(self.lon)
)
msg = '400 Client Error: Bad Request for url: {}'.format(url)
mock_get_forecast.side_effect = HTTPError(msg,)
response = darksky.setup_platform(self.hass, self.config, MagicMock())
self.assertFalse(response)
3
Example 8
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
3
Example 9
def __contains__(self, pk):
try:
self.get(self.endpoint + str(pk)).raise_for_status()
except requests.exceptions.HTTPError:
return False
else:
return True
3
Example 10
Project: okcupyd Source File: messaging.py
@property
def with_deleted_user(self):
try:
self.correspondent_profile.id
except exceptions.HTTPError:
return True
else:
return False
3
Example 11
Project: kpm Source File: test_kubernetes.py
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()
3
Example 12
Project: drawquest-web Source File: api.py
@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.")
3
Example 13
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
3
Example 14
Project: responses Source File: test_responses.py
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()
3
Example 15
Project: nailgun Source File: test_entity_mixins.py
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()
3
Example 16
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)
3
Example 17
Project: python-forecast.io Source File: test_forecastio.py
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'))
3
Example 18
Project: golem Source File: stream.py
@classmethod
def _split_headers(cls, header_data):
headers = {}
header_lines = ''.join(header_data).split(cls.short_sep)
if not len(header_lines):
raise HTTPError('Empty HTTP headers')
status, header_lines = header_lines[0].lower(), header_lines[1:]
for header_line in header_lines:
if header_line:
split_line = header_line.lower().split(':')
if len(split_line) >= 2:
key = split_line[0]
value = ''.join(split_line[1:]).strip()
headers[key] = value
return status, headers
3
Example 19
Project: hacker-news-digest Source File: test_embeddable_parser.py
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')
3
Example 20
Project: py-ipfs-api Source File: http.py
def _do_raise_for_status(self, response, content=None):
try:
response.raise_for_status()
except requests.exceptions.HTTPError as error:
# If we have decoded an error response from the server,
# use that as the exception message; otherwise, just pass
# the exception on to the caller.
if isinstance(content, dict) and 'Message' in content:
msg = content['Message']
six.raise_from(exceptions.ErrorResponse(msg, error), error)
else:
six.raise_from(exceptions.StatusError(error), error)
3
Example 21
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)
3
Example 22
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
3
Example 23
Project: django-konfera Source File: utils.py
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
3
Example 24
Project: puppetboard Source File: test_utils.py
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)
3
Example 25
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, '')
3
Example 26
Project: commcare-hq Source File: tasks.py
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)
3
Example 27
Project: twarc Source File: twarc.py
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']
3
Example 28
Project: paasta Source File: environment.py
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)
3
Example 29
Project: changemonger Source File: helpers.py
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))
3
Example 30
Project: rpc-openstack Source File: elasticsearch.py
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()
3
Example 31
Project: f5-common-python Source File: conftest.py
@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
3
Example 32
Project: paasta Source File: mesos_maintenance.py
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]]
3
Example 33
@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'})
3
Example 34
Project: plotly.py Source File: test_grid.py
@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)
3
Example 35
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
3
Example 36
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
3
Example 37
Project: home-assistant Source File: bbox.py
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
"""Get the latest data from the Bbox."""
import pybbox
try:
box = pybbox.Bbox()
self.data = box.get_ip_stats()
except requests.exceptions.HTTPError as error:
_LOGGER.error(error)
self.data = None
return False
3
Example 38
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)
3
Example 39
@classmethod
def _assert_headers(cls, data):
if not data:
raise HTTPError('Server returned empty headers')
status, header_lines = cls._split_headers(data)
cls._assert_status(status)
cls._assert_transfer_encoding(header_lines)
3
Example 40
Project: python-forecast.io Source File: test_forecastio.py
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'))
3
Example 41
@staticmethod
def _assert_status(entry):
status = entry.split(' ')
if len(status) < 3:
raise HTTPError('Invalid HTTP status: {}'
.format(status))
if status[0] != 'http/1.1':
raise HTTPError('Invalid HTTP version: {}'
.format(status[0]))
if status[1] != '200':
raise HTTPError('HTTP error: {}'
.format(status[1]))
3
Example 42
Project: vdirsyncer Source File: __init__.py
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())
3
Example 43
def api_access(method):
oss = OpenStackSwiftAPI
def wrapper(*args, **kwargs):
if not oss.is_initialized():
oss.update_token()
try:
return method(*args, **kwargs)
except requests.exceptions.HTTPError as exc:
if exc.response.status_code == 401:
# update access token
oss.update_token()
# re-run last request
return method(*args, **kwargs)
else:
raise
return wrapper
3
Example 44
Project: canvas Source File: api.py
@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.")
3
Example 45
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)
3
Example 46
Project: vdirsyncer Source File: test_caldav.py
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())
3
Example 47
Project: plotly.py Source File: test_grid.py
@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)
3
Example 48
Project: djangopackages Source File: bitbucket.py
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", [])
3
Example 49
Project: commcare-hq Source File: tasks.py
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))
3
Example 50
Project: twarc Source File: twarc.py
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']