Python requests.exceptions 模块,HTTPError() 实例源码

我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用requests.exceptions.HTTPError()

项目:ros-interop    作者:mcgill-robotics    | 项目源码 | 文件源码
def update_telemetry(navsat_msg, compass_msg):
    """Telemetry subscription callback.

    Args:
        navsat_msg: sensor_msgs/NavSatFix message.
        compass_msg: std_msgs/Float64 message in degrees.
    """
    try:
        client.post_telemetry(navsat_msg, compass_msg)
    except (ConnectionError, Timeout) as e:
        rospy.logwarn(e)
        return
    except (ValueError, HTTPError) as e:
        rospy.logerr(e)
        return
    except Exception as e:
        rospy.logfatal(e)
        return
项目:sentry-plugins    作者:getsentry    | 项目源码 | 文件源码
def request(self, method, path, data):
        # see https://pushover.net/api
        # We can no longer send JSON because pushover disabled incoming
        # JSON data: http://updates.pushover.net/post/39822700181/
        payload = {
            'user': self.userkey,
            'token': self.apikey,
        }
        payload.update(data)

        session = build_session()
        try:
            resp = getattr(session, method.lower())(
                url='{}{}'.format(self.base_url, path),
                data=payload,
                allow_redirects=False,
            )
            resp.raise_for_status()
        except HTTPError as e:
            raise ApiError.from_response(e.response)
        return resp.json()
项目:sentry-plugins    作者:getsentry    | 项目源码 | 文件源码
def request(self, data):
        payload = {
            'service_key': self.service_key,
        }
        payload.update(data)

        session = build_session()
        try:
            resp = session.post(
                url=INTEGRATION_API_URL,
                json=payload,
                allow_redirects=False,
            )
            resp.raise_for_status()
        except HTTPError as e:
            raise ApiError.from_response(e.response)
        return resp.json()
项目:sentry-plugins    作者:getsentry    | 项目源码 | 文件源码
def request(self, method, path, data=None, params=None):
        headers = {
            'Private-Token': self.token,
        }
        session = build_session()
        try:
            resp = getattr(session, method.lower())(
                url='{}/api/v3/{}'.format(self.url, path.lstrip('/')),
                headers=headers,
                json=data,
                params=params,
                allow_redirects=False,
            )
            resp.raise_for_status()
        except HTTPError as e:
            raise ApiError.from_response(e.response)
        return resp.json()
项目:sentry-plugins    作者:getsentry    | 项目源码 | 文件源码
def request(self, data):
        endpoint = 'https://alert.victorops.com/integrations/generic/20131114/alert/{}/{}'.format(
            self.api_key,
            self.routing_key,
        )

        session = build_session()
        try:
            resp = session.post(
                url=endpoint,
                json=data,
                allow_redirects=False,
            )
            resp.raise_for_status()
        except HTTPError as e:
            raise ApiError.from_response(e.response)
        return resp.json()
项目:marathon-acme    作者:praekeltfoundation    | 项目源码 | 文件源码
def raise_for_status(response):
    """
    Raises a `requests.exceptions.HTTPError` if the response did not succeed.
    Adapted from the Requests library:
    https://github.com/kennethreitz/requests/blob/v2.8.1/requests/models.py#L825-L837
    """
    http_error_msg = ''

    if 400 <= response.code < 500:
        http_error_msg = '%s Client Error for url: %s' % (
            response.code, uridecode(response.request.absoluteURI))

    elif 500 <= response.code < 600:
        http_error_msg = '%s Server Error for url: %s' % (
            response.code, uridecode(response.request.absoluteURI))

    if http_error_msg:
        raise HTTPError(http_error_msg, response=response)

    return response
项目:cvprac    作者:aristanetworks    | 项目源码 | 文件源码
def test_make_request_http_error(self):
        """ Test request http exception raised if hit on multiple nodes.
        """
        self.clnt.session = Mock()
        self.clnt.session.return_value = True
        self.clnt.session.get.side_effect = HTTPError('HTTPError')
        self.clnt._create_session = Mock()
        self.clnt.NUM_RETRY_REQUESTS = 2
        self.clnt.connect_timeout = 2
        self.clnt.node_cnt = 2
        self.clnt.url_prefix = 'https://1.1.1.1:7777/web'
        self.clnt._is_good_response = Mock(return_value='Good')
        self.assertIsNone(self.clnt.last_used_node)
        with self.assertRaises(HTTPError):
            self.clnt._make_request('GET', 'url', 2, {'data': 'data'})
        self.assertEqual(self.clnt.last_used_node, '1.1.1.1')
项目:cvprac    作者:aristanetworks    | 项目源码 | 文件源码
def test_make_request_no_session_error(self):
        """ Test request exception raised if hit on multiple nodes and
            _create_session fails to reset clnt.session.
        """
        self.clnt.session = Mock()
        self.clnt.session.return_value = True
        self.clnt.session.get.side_effect = HTTPError('HTTPError')
        self.clnt.NUM_RETRY_REQUESTS = 2
        self.clnt.connect_timeout = 0.01
        self.clnt.node_cnt = 2
        self.clnt.url_prefix = 'https://1.1.1.1:7777/web'
        self.clnt._is_good_response = Mock(return_value='Good')
        self.assertIsNone(self.clnt.last_used_node)
        with self.assertRaises(HTTPError):
            self.clnt._make_request('GET', 'url', 2, {'data': 'data'})
        self.assertEqual(self.clnt.last_used_node, '1.1.1.1')
项目:dnsimple2-python    作者:indradhanush    | 项目源码 | 文件源码
def test_create_with_invalid_data(self):
        with self.assertRaises(HTTPError) as e:
            self.client.domains.create(
                self.account,
                DomainResource(name='invalid-domain', account=self.account)
            )

        exception = e.exception
        self.assertEqual(exception.response.status_code, 400)
        self.assertEqual(exception.response.json(), {
            'message': 'Validation failed',
            'errors': {
                'name': ['is an invalid domain']
                }
            }
        )
项目:tap-freshdesk    作者:singer-io    | 项目源码 | 文件源码
def do_sync():
    logger.info("Starting FreshDesk sync")

    try:
        sync_tickets()
        sync_time_filtered("agents")
        sync_time_filtered("roles")
        sync_time_filtered("groups")
        # commenting out this high-volume endpoint for now
        #sync_time_filtered("contacts")
        sync_time_filtered("companies")
    except HTTPError as e:
        logger.critical(
            "Error making request to Freshdesk API: GET %s: [%s - %s]",
            e.request.url, e.response.status_code, e.response.content)
        sys.exit(1)

    logger.info("Completed sync")
项目:nn4nlp-code    作者:neubig    | 项目源码 | 文件源码
def upload_tasks(self, filenames, **kwargs):
        del kwargs
        try:
            for pattern in filenames:
                filenames = glob(pattern)
                if not filenames:
                    raise IOError("Not found: " + pattern)
                for passage in read_files_and_dirs(filenames):
                    task = self.upload_task(passage)
                    print("Submitted task %d" % task["id"])
                    yield task
        except HTTPError as e:
            try:
                raise ValueError(e.response.json()) from e
            except JSONDecodeError:
                raise ValueError(e.response.text) from e
项目:nn4nlp-code    作者:neubig    | 项目源码 | 文件源码
def main(filenames, write, **kwargs):
    uploader = TaskUploader(**kwargs)
    downloader = TaskDownloader(**kwargs)
    scores = []
    try:
        for pattern in filenames:
            filenames = glob(pattern)
            if not filenames:
                raise IOError("Not found: " + pattern)
            for ref in read_files_and_dirs(filenames):
                print("Converting passage " + ref.ID + "... ", end="")
                task = uploader.upload_task(ref)
                guessed = downloader.download_task(task["id"], write=write, **kwargs)
                score = evaluate(guessed, ref, **kwargs)
                print("F1=%.3f" % score.average_f1())
                scores.append(score)
    except HTTPError as e:
        try:
            raise ValueError(e.response.json()) from e
        except JSONDecodeError:
            raise ValueError(e.response.text) from e
    print()
    if len(scores) > 1:
        print("Aggregated scores:")
    Scores.aggregate(scores).print()
项目:trip    作者:littlecodersh    | 项目源码 | 文件源码
def _handle_exception(self, type_, value, tb):
        if self.final_callback:
            self._remove_timeout()
            if isinstance(value, StreamClosedError):
                if value.real_error is None:
                    value = HTTPError(599, 'Stream closed')
                else:
                    value = value.real_error
                m = MessageDelegate(self.request, None, None)
                m.code, m.reason = 599, value
            else:
                m = value

            self._run_callback(m)

            if hasattr(self, 'stream'):
                self.stream.close()
            return True
        else:
            return isinstance(value, StreamClosedError)
项目:danmu-bilibili    作者:saberxxy    | 项目源码 | 文件源码
def getSoup(start, stop):
    try:
        for number in range(start, stop + 1):
            username, uid = GetUsername.getUsername(number) #????????ID
            get_fans_uid = GetFansUid(number)
            fansuid, fansnumber = get_fans_uid.get_uids()  # ????id?????
            fansuid = fansuid.strip()[:-1] # ??????
            saveData(uid, username, fansnumber, fansuid)  # ?????
    except HTTPError:
        print("get page error: ", number)
        time.sleep(10)
        return getSoup(number, stop + 1)
    except Exception:
        pass


# ?????
项目:mfnf-pdf-export    作者:Lodifice    | 项目源码 | 文件源码
def retry(max_retries):
    """
    Retry a function `max_retries` times.
    taken from https://stackoverflow.com/questions/23892210/python-catch-timeout-and-repeat-request.
    """
    def retry(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            num_retries = 0
            while num_retries <= max_retries:
                try:
                    ret = func(*args, **kwargs)
                    break
                except HTTPError:
                    if num_retries == max_retries:
                        raise
                    num_retries += 1
                    time.sleep(1)
            return ret
        return wrapper
    return retry
项目:learn_requests    作者:shfanzie    | 项目源码 | 文件源码
def hard_requests():
    from requests import Request, Session
    s = Session()
    headers = {'User-Agent': 'fake1.3.4'}
    req = Request('GET', build_uri('user/emails'), auth=('shfanzie', '**********'), headers = headers)
    prepped = req.prepare()
    print prepped.body
    print prepped.headers

    try:
        resp = s.send(prepped, timeout=1)
        resp.raise_for_status()
    except exceptions.Timeout as e:
        print e.message
    except exceptions.HTTPError as e:
        print e.message
    else:
        print resp.status_code
        print resp.reason
        print resp.request.headers
        print resp.text
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def test_remove_from_channel_failed_contributor(mock_staff_client, status_code):
    """
    remove_from_channel should raise an exception if it fails to remove a user's contributor status,
    depending on the status code
    """
    channel_name = 'channel'
    discussion_username = 'user'
    response = mock_staff_client.channels.remove_contributor.return_value
    response.ok = False
    response.status_code = status_code
    response.raise_for_status.side_effect = HTTPError

    with pytest.raises(ContributorSyncException) as ex:
        api.remove_from_channel(channel_name, discussion_username)
    assert ex.value.args[0] == 'Unable to remove a contributor user from channel channel'
    mock_staff_client.channels.remove_contributor.assert_called_once_with(channel_name, discussion_username)
    mock_staff_client.channels.remove_subscriber.assert_called_once_with(channel_name, discussion_username)
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def test_remove_from_channel_failed_subscriber(mock_staff_client, status_code):
    """
    remove_from_channel should raise an exception if it fails to remove a user's subscriber status,
    depending on the status code
    """
    mock_staff_client.channels.remove_contributor.return_value.ok = True
    response = mock_staff_client.channels.remove_subscriber.return_value
    response.ok = False
    response.status_code = status_code
    response.raise_for_status.side_effect = HTTPError
    channel_name = 'channel'
    discussion_username = 'username'

    with pytest.raises(SubscriberSyncException) as ex:
        api.remove_from_channel(channel_name, discussion_username)
    assert ex.value.args[0] == 'Unable to remove a subscriber username from channel channel'
    mock_staff_client.channels.remove_subscriber.assert_called_once_with(channel_name, discussion_username)
    assert mock_staff_client.channels.remove_contributor.called is False
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def test_add_channel_failed_create_channel(mock_staff_client, mocker):
    """If client.channels.create fails an exception should be raised"""
    response_500 = Response()
    response_500.status_code = statuses.HTTP_500_INTERNAL_SERVER_ERROR
    mock_staff_client.channels.create.return_value.raise_for_status.side_effect = HTTPError(response=response_500)

    with pytest.raises(ChannelCreationException) as ex:
        api.add_channel(
            Search.from_dict({}),
            "title",
            "name",
            "public_description",
            "channel_type",
            123,
            456,
        )
    assert ex.value.args[0] == "Error creating channel name"
    mock_staff_client.channels.create.return_value.raise_for_status.assert_called_with()
    assert mock_staff_client.channels.create.call_count == 1
    assert PercolateQuery.objects.count() == 0
    assert Channel.objects.count() == 0
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def add_contributor_to_channel(channel_name, discussion_username):
    """
    Add user to channel as a contributor

    Args:
        channel_name (str): An open-discussions channel
        discussion_username (str): The username used by open-discussions
    """
    admin_client = get_staff_client()
    try:
        admin_client.channels.add_contributor(channel_name, discussion_username).raise_for_status()
    except HTTPError as ex:
        raise ContributorSyncException("Error adding contributor {user} to channel {channel}".format(
            user=discussion_username,
            channel=channel_name,
        )) from ex
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def add_moderator_to_channel(channel_name, discussion_username):
    """
    Add user to channel as a moderator

    Args:
        channel_name (str): An open-discussions channel
        discussion_username (str): The username used by open-discussions
    """
    admin_client = get_staff_client()
    try:
        admin_client.channels.add_moderator(channel_name, discussion_username).raise_for_status()
    except HTTPError as ex:
        raise ModeratorSyncException("Error adding moderator {user} to channel {channel}".format(
            user=discussion_username,
            channel=channel_name,
        )) from ex
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def add_subscriber_to_channel(channel_name, discussion_username):
    """
    Add a subscriber to channel

    Args:
        channel_name (str): An open-discussions channel
        discussion_username (str): The username used by open-discussions
    """
    admin_client = get_staff_client()
    try:
        admin_client.channels.add_subscriber(channel_name, discussion_username).raise_for_status()
    except HTTPError as ex:
        raise SubscriberSyncException("Error adding subscriber {user} to channel {channel}".format(
            user=discussion_username,
            channel=channel_name,
        )) from ex
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def remove_subscriber_from_channel(channel_name, discussion_username):
    """
    Remove subscriber from a channel

    Args:
        channel_name (str): An open-discussions channel
        discussion_username (str): The username used by open-discussions
    """
    admin_client = get_staff_client()

    try:
        admin_client.channels.remove_subscriber(channel_name, discussion_username).raise_for_status()
    except HTTPError as ex:
        raise SubscriberSyncException("Unable to remove a subscriber {user} from channel {channel}".format(
            user=discussion_username,
            channel=channel_name,
        )) from ex
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def test_update_cache_if_expired_http_errors(self, status_code, mock_enr):
        """
        Test for update_cache_if_expired in case a backend function raises an HTTPError
        """
        def raise_http_error(*args, **kwargs):  # pylint: disable=unused-argument
            """Mock function to raise an exception"""
            error = HTTPError()
            error.response = MagicMock()
            error.response.status_code = status_code
            raise error
        mock_enr.side_effect = raise_http_error
        if status_code in (400, 401):
            with self.assertRaises(InvalidCredentialStored):
                CachedEdxDataApi.update_cache_if_expired(self.user, self.edx_client, CachedEdxDataApi.ENROLLMENT)
        else:
            with self.assertRaises(HTTPError):
                CachedEdxDataApi.update_cache_if_expired(self.user, self.edx_client, CachedEdxDataApi.ENROLLMENT)
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def test_refresh_token_error_server(self, mock_refresh):
        """Test to check what happens when the OAUTH server returns an invalid status code"""
        def raise_http_error(*args, **kwargs):  # pylint: disable=unused-argument
            """Mock function to raise an exception"""
            error = HTTPError()
            error.response = MagicMock()
            error.response.status_code = 400
            raise error

        mock_refresh.side_effect = raise_http_error
        extra_data = {
            "updated_at": (self.now - timedelta(weeks=1)).timestamp(),
            "expires_in": 100  # seconds
        }
        self.update_social_extra_data(extra_data)
        res = self.get_with_mocked_enrollments()
        assert mock_refresh.called
        assert res.status_code == status.HTTP_400_BAD_REQUEST
项目:Dallinger    作者:Dallinger    | 项目源码 | 文件源码
def test_failure(self, handler):
        from requests.exceptions import HTTPError
        log = mock.Mock()
        with mock.patch('dallinger.command_line.requests.post') as mock_post:
            mock_post.return_value = mock.Mock(
                ok=False,
                json=mock.Mock(return_value={'message': u'msg!'}),
                raise_for_status=mock.Mock(side_effect=HTTPError)
            )
            with pytest.raises(HTTPError):
                handler('/some-launch-url', error=log)

        log.assert_has_calls([
            mock.call('Experiment launch failed, check web dyno logs for details.'),
            mock.call(u'msg!')
        ])
项目:irida-miseq-uploader    作者:phac-nml    | 项目源码 | 文件源码
def test_get_link_invalid_url_not_found(self,
                                            mock_validate_url_existence,
                                            mock_cs):

        mock_validate_url_existence.side_effect = [False]
        mock_cs.side_effect = [None]

        api = API.apiCalls.ApiCalls(
            client_id="",
            client_secret="",
            base_URL="",
            username="",
            password=""
        )

        targ_URL = "http://localhost:8080/api/"
        targ_key = "project"

        with self.assertRaises(request_HTTPError) as err:
            api.get_link(targ_URL, targ_key)

        self.assertTrue("not a valid URL" in str(err.exception))
        mock_validate_url_existence.assert_called_with(targ_URL,
                                                       use_session=True)
项目:git-repo    作者:guyzmo    | 项目源码 | 文件源码
def create(self, user, repo, add=False):
        try:
            repo = Repository.create(
                    RepositoryPayload(dict(
                        fork_policy=RepositoryForkPolicy.ALLOW_FORKS,
                        is_private=False
                    )),
                    repository_name=repo,
                    owner=user,
                    client=self.bb.client
            )
            if add:
                self.add(user=user, repo=repo.name, tracking=self.name)
        except HTTPError as err:
            if '400' in err.args[0].split(' '):
                raise ResourceExistsError('Project {} already exists on this account.'.format(repo)) from err
            raise ResourceError("Couldn't complete creation: {}".format(err)) from err
项目:git-repo    作者:guyzmo    | 项目源码 | 文件源码
def gist_list(self, gist=None):
        if not gist:
            for snippet in list(self.bb.snippetByOwner(owner=self.user)):
                if isinstance(snippet, Snippet):
                    yield (snippet.links['html']['href'], snippet.title)
        else:
            try:
                snippet = next(self.bb.snippetByOwnerAndSnippetId(owner=self.user, snippet_id=self._format_gist(gist)))
                for snippet_file in snippet.filenames:
                    yield ('N.A.',
                            0,
                            snippet_file)
            except HTTPError as err:
                if '404' in err.args[0].split(' '):
                    raise ResourceNotFoundError("Could not find snippet {}.".format(gist)) from err
                raise ResourceError("Couldn't fetch snippet details: {}".format(err)) from err
项目:git-repo    作者:guyzmo    | 项目源码 | 文件源码
def gist_fetch(self, gist, fname=None):
        gist = self._format_gist(gist)
        try:
            user = self.user
            snippet = next(self.bb.snippetByOwnerAndSnippetId(owner=user, snippet_id=gist))
        except HTTPError as err:
            if '404' in err.args[0].split(' '):
                raise ResourceNotFoundError("Could not find snippet {}.".format(gist)) from err
            raise ResourceError("Couldn't fetch snippet details: {}".format(err)) from err
        if len(snippet.filenames) == 1 and not fname:
            gist_file = snippet.filenames[0]
        else:
            if fname in snippet.filenames:
                gist_file = fname
            else:
                raise ResourceNotFoundError('Could not find file within gist.')

        return self.bb.client.session.get(
                    'https://bitbucket.org/!api/2.0/snippets/{}/{}/files/{}'.format(user, gist, gist_file)
                ).content.decode('utf-8')
项目:wazo-admin-ui    作者:wazo-pbx    | 项目源码 | 文件源码
def _configure_login(self):
        login_manager = LoginManager()
        login_manager.init_app(app)

        @login_manager.user_loader
        def load_token(token):
            try:
                response = AuthClient().token.get(token)
            except HTTPError:
                return None
            except requests.ConnectionError:
                logger.warning('Wazo authentication server connection error')
                return None
            token = response.get('token')
            if not token:
                return None
            return UserUI(token, response.get('auth_id'))
项目:wazo-admin-ui    作者:wazo-pbx    | 项目源码 | 文件源码
def post(self):
        form = self.form()
        resources = self._map_form_to_resources_post(form)

        if not form.csrf_token.validate(form):
            flash_basic_form_errors(form)
            return self._new(form)

        try:
            self.service.create(resources)
        except HTTPError as error:
            form = self._fill_form_error(form, error)
            self._flash_http_error(error)
            return self._new(form)

        flash(_('%(resource)s: Resource has been created', resource=self.resource), 'success')
        return self._redirect_for('index')
项目:wazo-admin-ui    作者:wazo-pbx    | 项目源码 | 文件源码
def put(self, id):
        form = self.form()
        if not form.csrf_token.validate(form):
            flash_basic_form_errors(form)
            return self._get(id, form)

        resources = self._map_form_to_resources_put(form, id)
        try:
            self.service.update(resources)
        except HTTPError as error:
            form = self._fill_form_error(form, error)
            self._flash_http_error(error)
            return self._get(id, form)

        flash(_('%(resource)s: Resource has been updated', resource=self.resource), 'success')
        return self._redirect_for('index')
项目:wazo-admin-ui    作者:wazo-pbx    | 项目源码 | 文件源码
def validate(self):
        super(LoginForm, self).validate()
        try:
            response = AuthClient(username=self.username.data,
                                  password=self.password.data).token.new('xivo_admin', expiration=60*60*12)
        except HTTPError as e:
            if unauthorized(e):
                self.username.errors.append(USERNAME_PASSWORD_ERROR)
                self.password.errors.append(USERNAME_PASSWORD_ERROR)
                return False
            raise ValidationError(l_('Error with Wazo authentication server: %(error)s', error=e.message))
        except requests.ConnectionError:
            raise ValidationError(l_('Wazo authentication server connection error'))

        self.user = UserUI(response['token'], response['auth_id'])

        return True
项目:openqa_review    作者:okurz    | 项目源码 | 文件源码
def reminder_comment_on_issues(report, min_days_unchanged=MIN_DAYS_UNCHANGED):
    processed_issues = set()
    report.report = SortedDict({p: pr for p, pr in iteritems(report.report) if isinstance(pr, ProductReport)})
    for product, pr in iteritems(report.report):
        for arch, ar in iteritems(pr.reports):
            for issue_status, issue_types in iteritems(ar.issues):
                for issue_type, ies in iteritems(issue_types):
                    for ie in ies:
                        issue = ie.bug
                        if issue:
                            bugref = issue.bugref.replace('bnc', 'bsc').replace('boo', 'bsc')
                            if bugref not in processed_issues:
                                try:
                                    reminder_comment_on_issue(ie, min_days_unchanged)
                                except HTTPError as e:  # pragma: no cover
                                    log.error("Encountered error trying to post a reminder comment on issue '%s': %s. Skipping." % (ie, e))
                                    continue
                                processed_issues.add(bugref)
项目:jira_reporting_scripts    作者:andrew-hamlin-sp    | 项目源码 | 文件源码
def get_json(self, url, *args, **kwargs):
        '''Returns a JSON payload.

        Given a generator expression, this will return each next payload.

        Example:
        json_response = (r for r in [{...}, {...}])
        '''
        self._actual_url = url
        if self._raise401:
            response = Response()
            response.status_code = 401
            response.reason = 'Unauthorized'
            raise HTTPError(response.status_code, response.reason, response=response)

        if isgenerator(self.json_response):
            return next(self.json_response)
        else:
            return self.json_response
项目:lets-do-dns    作者:Jitsusama    | 项目源码 | 文件源码
def test_properly_raises_correct_record_failure_on_related_method_error(
        mocker, method, exception):
    stub_error = HTTPError()
    stub_raise_for_status = mocker.MagicMock(side_effect=stub_error)
    stub_request = mocker.MagicMock(spec=requests.Request, method=method)
    stub_response = mocker.MagicMock(
        spec=requests.Response,
        raise_for_status=stub_raise_for_status, request=stub_request)

    class_to_mock = 'lets_do_dns.do_domain.response.{}'.format(
        exception.__name__)
    mock_record_failure = mocker.patch(
        class_to_mock, return_value=exception)

    with pytest.raises(exception):
        Response(stub_response)

    mock_record_failure.assert_called_once_with(stub_error)
项目:python-steamcommunity    作者:DrBomb    | 项目源码 | 文件源码
def GetTradeOffers(self,**kwargs):
        method = "/GetTradeOffers/v1/"
        arguments = {
                'key':self.key,
                'get_sent_offers':int(kwargs.get('get_sent_offers',1)),
                'get_received_offers':int(kwargs.get('get_received_offers',0)),
                'get_descriptions':int(kwargs.get('get_descriptions',0)),
                'active_only':int(kwargs.get('active_only',1)),
                'historical_only':int(kwargs.get('historical_only',0)),
                }
        if "language" in kwargs.keys():
            arguments['language'] = kwargs['language']
        if "time_historical_cutoff" in kwargs.keys():
            arguments['time_historical_cutoff'] = kwargs['time_historical_cutoff']
        response = self.request.get(self.baseURL+self.endpoint+method,params=arguments)
        try:
            response.raise_for_status()
            return response.json()
        except HTTPError as e:
            if e.response.status_code != 403:
                raise Exception(e.message)
            raise InvalidAPIKey("This API key is invalid")
项目:python-steamcommunity    作者:DrBomb    | 项目源码 | 文件源码
def GetTradeOffer(self,tradeofferid,**kwargs):
        method = "/GetTradeOffer/v1/"
        arguments = {
                'key':self.key,
                'tradeofferid':tradeofferid,
                }
        if "language" in kwargs.keys():
            arguments['language'] = kwargs['language']
        response = self.request.get(self.baseURL+self.endpoint+method,params=arguments)
        try:
            response.raise_for_status()
            return response.json()
        except HTTPError as e:
            if e.response.status_code != 403:
                raise Exception(e.message)
            raise InvalidAPIKey("This API key is invalid")
项目:merge-bot    作者:jasonkuster    | 项目源码 | 文件源码
def fetch_prs(self):
        """Gets the PRs for the configured repository.

        Returns:
            A tuple of (pr_list, error).
            pr_list is an iterable of GithubPRs if successful, otherwise empty.
            error is None if successful, or the error message otherwise.
        """
        try:
            prs = self.get(GITHUB_PULLS_ENDPOINT)
            return [GithubPR(self, pr) for pr in prs], None
        except HTTPError as exc:
            return [], 'Non-200 HTTP Code Received: {}'.format(exc)
        except Timeout as exc:
            return [], 'Request timed out: {}'.format(exc)
        except RequestException as exc:
            return [], 'Catastrophic error in requests: {}'.format(exc)
项目:merge-bot    作者:jasonkuster    | 项目源码 | 文件源码
def get(self, endpoint):
        """get makes a GET request against a specified endpoint.

        Args:
            endpoint: URL to which to make the GET request. URL is relative
            to https://api.github.com/repos/{self.org}/{self.repo}/
        Returns:
            JSON object retrieved from the endpoint.
        Raises:
            HTTPError: if we get an HTTP error status.
            Timeout: for timeouts.
            RequestException: for other assorted exceptional cases.
        """
        url = urlparse.urljoin(self.repo_url, endpoint)
        resp = requests.get(url, auth=(BOT_NAME, self.bot_key))
        if resp.status_code is 200:
            return resp.json()
        resp.raise_for_status()
项目:xivo-ctid-ng    作者:wazo-pbx    | 项目源码 | 文件源码
def _connect(self):
        logger.debug('ARI client listening...')
        try:
            with self._running():
                self.client.run(apps=[APPLICATION_NAME])
        except socket.error as e:
            if e.errno == errno.EPIPE:
                # bug in ari-py when calling client.close(): ignore it and stop
                logger.error('Error while listening for ARI events: %s', e)
                return
            else:
                self._connection_error(e)
        except (WebSocketException, HTTPError) as e:
            self._connection_error(e)
        except ValueError:
            logger.warning('Received non-JSON message from ARI... disconnecting')
            self.client.close()
项目:sapi-python-client    作者:keboola    | 项目源码 | 文件源码
def test_delete_table(self):
        file, path = tempfile.mkstemp(prefix='sapi-test')
        with open(path, 'w') as csv_file:
            writer = csv.DictWriter(csv_file, fieldnames=['col1', 'col2'],
                                    lineterminator='\n', delimiter=',',
                                    quotechar='"')
            writer.writeheader()
            writer.writerow({'col1': 'ping', 'col2': 'pong'})
        table_id = self.tables.create(name='some-table', file_path=path,
                                      bucket_id='in.c-py-test-tables')
        table_info = self.tables.detail(table_id)
        self.assertEqual(table_id, table_info['id'])
        self.tables.delete(table_id)
        try:
            self.tables.detail('some-totally-non-existent-table')
        except exceptions.HTTPError as e:
            if e.response.status_code != 404:
                raise
项目:ros-interop    作者:mcgill-robotics    | 项目源码 | 文件源码
def publish_obstacles(timer_event):
    """Requests and publishes obstacles.

    Args:
        timer_event: ROS TimerEvent.
    """
    try:
        moving_obstacles, stationary_obstacles = client.get_obstacles(
            frame, lifetime)
    except (ConnectionError, Timeout) as e:
        rospy.logwarn(e)
        return
    except (ValueError, HTTPError) as e:
        rospy.logerr(e)
        return
    except Exception as e:
        rospy.logfatal(e)
        return

    moving_pub.publish(moving_obstacles)
    stationary_pub.publish(stationary_obstacles)
项目:ros-interop    作者:mcgill-robotics    | 项目源码 | 文件源码
def get_active_mission(req):
    """ Service to update mission information with current active mission.

    Args:
        req: Request of type Trigger.

    Returns:
        TriggerResponse with true, false for success, failure.
    """
    with lock:
        global msgs
        try:
            msgs = client.get_active_mission(frame)
        except (ConnectionError, Timeout) as e:
            rospy.logwarn(e)
            return False, str(e)
        except (ValueError, HTTPError) as e:
            rospy.logerr(e)
            return False, str(e)

    rospy.loginfo("Using active mission")
    return True, "Success"
项目:zeus    作者:getsentry    | 项目源码 | 文件源码
def _dispatch(
        self, method: str, path: str, headers: dict=None, json: dict=None, params: dict=None
    ):
        if path.startswith(('http:', 'https:')):
            url = path
        else:
            url = '{}{}'.format(self.url, path)

        try:
            resp = requests.request(
                method=method,
                url=url,
                headers=headers,
                json=json,
                params=params,
                allow_redirects=True,
            )
            resp.raise_for_status()
        except HTTPError as e:
            raise ApiError.from_response(e.response)

        if resp.status_code == 204:
            return {}

        return BaseResponse.from_response(resp)
项目:singularity-python    作者:singularityware    | 项目源码 | 文件源码
def download(self,url,file_name,headers=None,show_progress=True):
        '''stream to a temporary file, rename on successful completion
        :param file_name: the file name to stream to
        :param url: the url to stream from
        :param headers: additional headers to add
        '''

        fd, tmp_file = tempfile.mkstemp(prefix=("%s.tmp." % file_name)) 
        os.close(fd)
        response = self.stream(url,headers=headers,stream_to=tmp_file)

        if isinstance(response, HTTPError):
            bot.error("Error downloading %s, exiting." %url)
            sys.exit(1)
        shutil.move(tmp_file, file_name)
        return file_name
项目:pyhashdd    作者:hashdd    | 项目源码 | 文件源码
def download(url, f):
    print 'Downloading: {}'.format(url)
    try:
        r = requests.get(url, stream=True)
        r.raise_for_status()

        filename = basename(urlparse(r.url).path)

        if not filename_candidate(filename):
            if 'content-disposition' in r.headers:
                filename = re.findall("filename=(.+)", r.headers['content-disposition'])
            else:
                filename = 'unknown'

        for chunk in r.iter_content(chunk_size=1024): 
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)
    except (HTTPError, ConnectionError) as e:
        print 'Exception raised while downloading file: {}'.format(e)
        return None 

    f.seek(0)
    return filename
项目:Harbor-CLI    作者:srishanbhattarai    | 项目源码 | 文件源码
def execute(self):
        ''' Invite a user to the current project. '''
        if not android.is_android():
            logger().error('You are not in a valid Android project.')
            sys.exit(1)

        email, password = getlogincredentials()

        try:
            Firebase().login_with_email(email, password)
        except exceptions.HTTPError:
            logger().error('Cannot login. Please verify credentials.')
            sys.exit(1)

        self.projectdetails = android.project_details()
        remoteprojectdetails = self.get_remote_details()

        if remoteprojectdetails is None:
            logger().error(
                'This project has not been registered. Please run `harbor register --help`'
            )

        self.update_database()
        logger().info('Invitation successful.')