Python requests.HTTPError() Examples

The following are 30 code examples of requests.HTTPError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module requests , or try the search function .
Example #1
Source File: webclient.py    From ibllib with MIT License 7 votes vote down vote up
def _generic_request(self, reqfunction, rest_query, data=None):
        # if the data is a dictionary, it has to be converted to json text
        if isinstance(data, dict):
            data = json.dumps(data)
        # makes sure the base url is the one from the instance
        rest_query = rest_query.replace(self._base_url, '')
        if not rest_query.startswith('/'):
            rest_query = '/' + rest_query
        logger_.debug(self._base_url + rest_query)
        r = reqfunction(self._base_url + rest_query, stream=True, headers=self._headers, data=data)
        if r and r.status_code in (200, 201):
            return json.loads(r.text)
        elif r and r.status_code == 204:
            return
        else:
            logger_.error(self._base_url + rest_query)
            logger_.error(r.text)
            raise(requests.HTTPError(r)) 
Example #2
Source File: action.py    From insightconnect-plugins with MIT License 6 votes vote down vote up
def run(self, params={}):
        input_classification = params.get("classification")
        offset = params.get("offset")
        limit = params.get("limit")

        params = dict()
        if input_classification is not None:
            params["classification"] = input_classification
        params["offset"] = offset
        params["limit"] = limit

        try:
            response = self.connection.CLIENT.get(self.__URL, params=params)
            applications = response.json()["items"]
            applications = komand.helper.clean(applications)
        except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error:
            raise error

        return {"applications": applications} 
Example #3
Source File: action.py    From insightconnect-plugins with MIT License 6 votes vote down vote up
def run(self, params={}):
        org_id = params.get("organization_id")
        inc_id = params.get("incident_id")
        artifact = params.get("artifact")

        url = self.connection.API_BASE + "/orgs/{org_id}/incidents/{inc_id}/artifacts".format(org_id=org_id,
                                                                                              inc_id=inc_id)

        artifact = json.dumps(artifact)

        self.logger.info("Creating artifact on incident %s..." % inc_id)
        try:
            response = self.connection.SESSION.post(url=url, data=artifact)
            new_artifact = response.json()[0]
            new_artifact = komand.helper.clean(new_artifact)
        except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error:
            self.logger.error("Error: %s" % error)
            raise

        return {"artifact": new_artifact} 
Example #4
Source File: action.py    From insightconnect-plugins with MIT License 6 votes vote down vote up
def run(self, params={}):
        org_id = params.get("organization_id")
        inc_id = params.get("incident_id")

        url = self.connection.API_BASE + "/orgs/{org_id}/incidents/{inc_id}/artifacts".format(org_id=org_id,
                                                                                              inc_id=inc_id)

        self.logger.info("Retrieving artifacts for incident %s..." % inc_id)
        try:
            response = self.connection.SESSION.get(url)
            artifacts = response.json()
            artifacts = komand.helper.clean(artifacts)
        except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error:
            self.logger.error("Error: %s" % error)
            raise

        return {"artifacts": artifacts} 
Example #5
Source File: action.py    From insightconnect-plugins with MIT License 6 votes vote down vote up
def run(self, params={}):
        org_id = params.get("organization_id")
        inc_id = params.get("incident_id")

        url = self.connection.API_BASE + "/orgs/{org_id}/incidents/{inc_id}".format(org_id=org_id,
                                                                                    inc_id=inc_id)

        self.logger.info("Creating incident for organization %s..." % org_id)
        try:
            response = self.connection.SESSION.delete(url=url)
            status = response.json()
            status = komand.helper.clean(status)
        except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error:
            self.logger.error("Error: %s" % error)
            raise

        return {"status": status} 
Example #6
Source File: action.py    From insightconnect-plugins with MIT License 6 votes vote down vote up
def run(self, params={}):
        org_id = params.get("organization_id")
        query = params.get("query")

        url = self.connection.API_BASE + "/orgs/{org_id}/incidents/query".format(org_id=org_id)

        self.logger.info("Querying...")
        try:
            response = self.connection.SESSION.post(url=url, data=query)
            incidents = response.json()
            incidents = komand.helper.clean(incidents)
        except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error:
            self.logger.error("Error: %s" % error)
            raise

        return {"incidents": incidents} 
Example #7
Source File: action.py    From insightconnect-plugins with MIT License 6 votes vote down vote up
def run(self, params={}):
        org_id = params.get("organization_id")
        inc_id = params.get("incident_id")
        url = self.connection.API_BASE + "/orgs/{org_id}/incidents/{inc_id}".format(org_id=org_id,
                                                                                    inc_id=inc_id)

        self.logger.info("Retrieving incident %s..." % inc_id)
        try:
            response = self.connection.SESSION.get(url)
            incident = response.json()
            incident = komand.helper.clean(incident)
        except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error:
            self.logger.error("Error: %s" % error)
            raise

        return {"incident": incident} 
Example #8
Source File: action.py    From insightconnect-plugins with MIT License 6 votes vote down vote up
def run(self, params={}):
        org_id = params.get("organization_id")
        inc_id = params.get("incident_id")
        artifact_id = params.get("artifact_id")

        url = self.connection.API_BASE + "/orgs/{org_id}/incidents/{inc_id}/artifacts/{artifact_id}".format(org_id=org_id,
                                                                                                            inc_id=inc_id,
                                                                                                            artifact_id=artifact_id)

        self.logger.info("Retrieving artifact for incident %s..." % inc_id)
        try:
            response = self.connection.SESSION.get(url)
            artifact = response.json()
            artifact = komand.helper.clean(artifact)
        except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error:
            self.logger.error("Error: %s" % error)
            raise

        return {"artifact": artifact} 
Example #9
Source File: test_utils.py    From Jike-Metro with MIT License 6 votes vote down vote up
def test_extract_link(self):
        success_response = {'success': True, 'data': 'link'}
        responses.add(responses.POST, constants.ENDPOINTS['extract_link'],
                      json=success_response,
                      status=200)
        responses.add(responses.POST, constants.ENDPOINTS['extract_link'],
                      status=401)
        # success call
        result = utils.extract_link(self.session, 'https://www.ojbk.com')
        self.assertEqual(result, 'link')
        self.assertEqual(len(responses.calls), 1)
        self.assertEqual(responses.calls[0].request.url, constants.ENDPOINTS['extract_link'])
        self.assertEqual(responses.calls[0].response.json(), success_response)
        # failed call
        with self.assertRaises(requests.HTTPError) as cm:
            utils.extract_link(self.session, 'https://www.ojbk.com')
        self.assertEqual(len(responses.calls), 2)
        self.assertEqual(cm.exception.response.status_code, 401) 
Example #10
Source File: action.py    From insightconnect-plugins with MIT License 6 votes vote down vote up
def run(self, params={}):
        org_id = params.get("organization_id")
        inc_id = params.get("incident_id")
        artifact_id = params.get("artifact_id")

        url = self.connection.API_BASE + "/orgs/{org_id}/incidents/{inc_id}/artifacts/{artifact_id}".format(org_id=org_id,
                                                                                                            inc_id=inc_id,
                                                                                                            artifact_id=artifact_id)

        self.logger.info("Deleting artifact %s on incident %s..." % (artifact_id, inc_id))
        try:
            response = self.connection.SESSION.delete(url)
            status = response.json()
            status = komand.helper.clean(status)
        except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error:
            self.logger.error("Error: %s" % error)
            raise

        return {"status": status} 
Example #11
Source File: action.py    From insightconnect-plugins with MIT License 6 votes vote down vote up
def run(self, params={}):
        org_id = params.get("organization_id")
        inc_id = params.get("incident_id")
        patch = params.get("patch")

        url = self.connection.API_BASE + "/orgs/{org_id}/incidents/{inc_id}".format(org_id=org_id,
                                                                                    inc_id=inc_id)

        patch = json.dumps(patch)

        self.logger.info("Patching incident %s..." % inc_id)
        try:
            response = self.connection.SESSION.patch(url=url, data=patch)
            patch_status = response.json()
            patch_status = komand.helper.clean(patch_status)
        except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error:
            self.logger.error("Error: %s" % error)
            raise

        return {"patch_status": patch_status} 
Example #12
Source File: action.py    From insightconnect-plugins with MIT License 6 votes vote down vote up
def run(self, params={}):
        org_id = params.get("organization_id")
        inc_id = params.get("incident_id")
        url = self.connection.API_BASE + "/orgs/{org_id}/incidents/{inc_id}/tasks".format(org_id=org_id,
                                                                                          inc_id=inc_id)
        json_body = params.get("body")
        json_body = json.dumps(json_body)

        try:
            response = self.connection.SESSION.post(url=url, data=json_body)
            identifier = response.json()["id"]

            if response.status_code != 200:
                self.logger.error("Error occurred - check the JSON body and ensure the data is correct.")

        except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error:
            self.logger.error("Error %d: %s" % (response.status_code, error))
            raise

        return {"identifier": identifier} 
Example #13
Source File: action.py    From insightconnect-plugins with MIT License 6 votes vote down vote up
def run(self, params={}):
        org_id = params.get("organization_id")
        inc_id = params.get("incident_id")
        artifact_id = params.get("artifact_id")
        artifact = params.get("artifact")

        url = self.connection.API_BASE + "/orgs/{org_id}/incidents/{inc_id}/artifacts/{artifact_id}".format(org_id=org_id,
                                                                                                            inc_id=inc_id,
                                                                                                            artifact_id=artifact_id)

        artifact = json.dumps(artifact)

        self.logger.info("Updating artifact %s..." % artifact_id)
        try:
            response = self.connection.SESSION.put(url=url, data=artifact)
            updated_artifact = response.json()
            updated_artifact = komand.helper.clean(updated_artifact)
        except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error:
            self.logger.error("Error: %s" % error)
            raise

        return {"artifact": updated_artifact} 
Example #14
Source File: client.py    From pylivy with MIT License 6 votes vote down vote up
def get_batch_log(
        self, batch_id: int, from_: int = None, size: int = None
    ) -> Optional[BatchLog]:
        """Get logs for a batch.

        :param batch_id: The ID of the batch.
        :param from_: The line number to start getting logs from.
        :param size: The number of lines of logs to get.
        """
        params = {}
        if from_ is not None:
            params["from"] = from_
        if size is not None:
            params["size"] = size
        try:
            data = self._client.get(f"/batches/{batch_id}/log", params=params)
        except requests.HTTPError as e:
            if e.response.status_code == 404:
                return None
            else:
                raise
        return BatchLog.from_json(data) 
Example #15
Source File: test_client.py    From Jike-Metro with MIT License 6 votes vote down vote up
def test_create_my_post(self):
        mock_response = Mock()
        mock_response.status_code = 200
        mock_response.json.return_value = {'success': True, 'data': {}}
        mock_response.raise_for_status.return_value = None
        self.mock_jike_session.post.return_value = mock_response
        result = self.jike_client.create_my_post('jike')
        self.assertIsInstance(result, tuple)
        # failed by post no string content
        with self.assertRaises(AssertionError):
            self.jike_client.create_my_post(123)
        # failed call by post both link and picture at one time
        with self.assertRaises(ValueError):
            self.jike_client.create_my_post('jike', link='a', pictures='b')
        mock_response.reset_mock()
        # failed call by post failed
        mock_response.json.return_value = {'success': False}
        with self.assertRaises(RuntimeError):
            self.jike_client.create_my_post('jike')
        # failed call by server error
        mock_response.status_code = 401
        mock_response.raise_for_status.side_effect = requests.HTTPError()
        with self.assertRaises(requests.HTTPError):
            self.jike_client.create_my_post('jike') 
Example #16
Source File: test_client.py    From Jike-Metro with MIT License 6 votes vote down vote up
def test__collect_action(self):
        mock_message = Mock()
        mock_message.type = 'OFFICIAL_MESSAGE'
        mock_message.id = '123'

        mock_response = Mock()
        mock_response.status_code = 200
        mock_response.json.return_value = {'success': True}
        mock_response.raise_for_status.return_value = None
        self.mock_jike_session.post.return_value = mock_response
        result = self.jike_client._collect_action(mock_message, 'collect_it')
        self.assertTrue(result)
        # failed call by assertion
        mock_message.type = ''
        with self.assertRaises(AssertionError):
            self.jike_client._collect_action(mock_message, 'uncollect_it')
        # failed by server error
        mock_message.type = 'ORIGINAL_POST'
        mock_response.status_code = 403
        mock_response.raise_for_status.side_effect = requests.HTTPError()
        with self.assertRaises(requests.HTTPError):
            self.jike_client._collect_action(mock_message, 'collect_it') 
Example #17
Source File: action.py    From insightconnect-plugins with MIT License 6 votes vote down vote up
def run(self, params={}):
        org_id = params.get("organization_id")
        incident = params.get("incident")

        url = self.connection.API_BASE + "/orgs/{org_id}/incidents".format(org_id=org_id)

        incident = json.dumps(incident)

        self.logger.info("Creating incident for organization %s..." % org_id)
        try:
            response = self.connection.SESSION.post(url=url, data=incident)
            new_incident = response.json()
            new_incident = komand.helper.clean(new_incident)
        except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error:
            self.logger.error("Error: %s" % error)
            raise

        return {"incident": new_incident} 
Example #18
Source File: action.py    From insightconnect-plugins with MIT License 6 votes vote down vote up
def run(self, params={}):
        org_id = params.get("organization_id")
        inc_id = params.get("incident_id")

        url = self.connection.API_BASE + "/orgs/{org_id}/incidents/{inc_id}/tasks".format(org_id=org_id,
                                                                                          inc_id=inc_id)

        self.logger.info("Retrieving tasks for incident %s..." % inc_id)
        try:
            response = self.connection.SESSION.get(url)
            tasks = response.json()
            tasks = komand.helper.clean(tasks)
        except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error:
            self.logger.error("Error: %s" % error)
            raise

        return {"tasks": tasks} 
Example #19
Source File: action.py    From insightconnect-plugins with MIT License 6 votes vote down vote up
def run(self, params={}):
        #required param, so we can assume it exists
        email_address = params.get(Input.EMAIL_ADDRESS)
        token = self.connection.access_token

        headers = {"Authorization": "Bearer %s" % token, "Content-Type": "application/json"}
        base_url = f"https://graph.microsoft.com/v1.0/{self.connection.tenant_id}/users?$filter=userPrincipalName eq '{email_address}'"

        try:
            response = requests.get(base_url, headers=headers)
        except requests.HTTPError as e:
            raise PluginException("Error with the Lookup User by Email request.", data=str(e))

        try:
            #this will throw any 4xx error
            response.raise_for_status()
        except Exception as e:
            raise PluginException(f"The response from Office365 indicated something went wrong: {response.status_code}",
                                  data=response.text)
        return {Output.USER: response.json()} 
Example #20
Source File: TestRailListener.py    From robotframework-testrail with Apache License 2.0 6 votes vote down vote up
def _update_case_description(self, attributes: JsonDict, case_id: str, name: str,
                                 references: Optional[str]) -> None:
        """ Update test case description in TestRail

        *Args:* \n
            _attributes_ - attributes of test case in Robot Framework;\n
            _case_id_ - case id;\n
            _name_ - test case name;\n
            _references_ - test references.
        """
        logger.info(f"[TestRailListener] update of test {case_id} in TestRail")
        description = f"{attributes['doc']}\nPath to test: {attributes['longname']}"
        request_fields: Dict[str, Union[str, int, None]] = {
            'title': name, 'type_id': self.TESTRAIL_CASE_TYPE_ID_AUTOMATED,
            'custom_case_description': description, 'refs': references}
        try:
            json_result = self.tr_client.update_case(case_id, request_fields)
            result = json.dumps(json_result, sort_keys=True, indent=4)
            logger.info(f"[TestRailListener] result for method update_case: {result}")
        except requests.HTTPError as error:
            logger.error(f"[TestRailListener] http error, while execute request:\n{error}") 
Example #21
Source File: docker-registry-show.py    From docker-registry-client with Apache License 2.0 6 votes vote down vote up
def show_manifest(self, client, repository, ref):
        try:
            repo = client.repository(repository)
        except requests.HTTPError as e:
            if e.response.status_code == requests.codes.not_found:
                print("Repository {0} not found".format(repository))
            else:
                raise
        else:
            assert client.api_version in [1, 2]
            if client.api_version == 2:
                manifest, digest = repo.manifest(ref)
                print("Digest: {0}".format(digest))
                print("Manifest:")
                print(json.dumps(manifest, indent=2, sort_keys=True))
            else:
                image = repo.image(ref)
                image_json = image.get_json()
                print("Image ID: {0}".format(image.image_id))
                print("Image JSON:")
                print(json.dumps(image_json, indent=2, sort_keys=True)) 
Example #22
Source File: action.py    From insightconnect-plugins with MIT License 6 votes vote down vote up
def run(self, params={}):
        token = self.connection.access_token

        base_url = "https://graph.microsoft.com/v1.0/subscribedSkus/"
        headers = {"Authorization": "Bearer %s" % token}

        try:
            response = requests.get(base_url, headers=headers)
        except requests.HTTPError:
            raise PluginException(cause=f"There was an issue with the Get Subscribed SKUs user request. Double-check the username: {user_principal_name}",
                        data=response.text)
        if response.status_code == 200:
            return {Output.SKU_ITEM: response.json()["value"]}
        else:
             PluginException(cause=f"The response from Office365 indicated something went wrong: {response.status_code}",
                              data=response.text) 
Example #23
Source File: action.py    From insightconnect-plugins with MIT License 6 votes vote down vote up
def run(self, params={}):
        user_principal_name = params.get(Input.USER_PRINCIPAL_NAME)
        location = params.get(Input.LOCATION)
        token = self.connection.access_token

        base_url = "https://graph.microsoft.com/v1.0/users/%s" % user_principal_name
        headers = {"Authorization": "Bearer %s" % token, "Content-Type": "application/json",}
        
        body = {
            "usageLocation": location
        }
        
        try:
            response = requests.patch(base_url, json=body, headers=headers)
        except requests.HTTPError:
            raise PluginException(cause=f"There was an issue updating the user's location. Double-check the user name: {user_principal_name}",
                        data=response.text)
        if response.status_code == 204:
            return {Output.SUCCESS: True}
        else:
            raise PluginException(f"The response from Office365 indicated something went wrong: {response.status_code}",
                              data=response.text) 
Example #24
Source File: action.py    From insightconnect-plugins with MIT License 6 votes vote down vote up
def run(self, params={}):
        user_principal_name = params.get(Input.USER_PRINCIPAL_NAME)
        token = self.connection.access_token

        base_url = 'https://graph.microsoft.com/beta/users/%s' % user_principal_name
        headers = {'Authorization': 'Bearer %s' % token}

        try:
            response = requests.delete(base_url, headers=headers)
        except requests.HTTPError:
            raise PluginException(cause=f"There was an issue with the Delete User request. Double-check the username: {user_principal_name}",
                                  data=response.text)
        if response.status_code == 204:
            success = True
            return {Output.SUCCESS: success}
        else:
            raise PluginException(cause="The response from Office365 indicated something went wrong: {response.status_code}",
                                  data=response.text) 
Example #25
Source File: response.py    From pyspider with Apache License 2.0 6 votes vote down vote up
def raise_for_status(self, allow_redirects=True):
        """Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred."""

        if self.status_code == 304:
            return
        elif self.error:
            if self.traceback:
                six.reraise(Exception, Exception(self.error), Traceback.from_string(self.traceback).as_traceback())
            http_error = HTTPError(self.error)
        elif (self.status_code >= 300) and (self.status_code < 400) and not allow_redirects:
            http_error = HTTPError('%s Redirection' % (self.status_code))
        elif (self.status_code >= 400) and (self.status_code < 500):
            http_error = HTTPError('%s Client Error' % (self.status_code))
        elif (self.status_code >= 500) and (self.status_code < 600):
            http_error = HTTPError('%s Server Error' % (self.status_code))
        else:
            return

        http_error.response = self
        raise http_error 
Example #26
Source File: api.py    From fac with MIT License 6 votes vote down vote up
def login(self, username, password, require_ownership=False):
        resp = self.session.post(
            self.login_url,
            params=dict(require_game_ownership=int(require_ownership)),
            data=dict(username=username, password=password)
        )

        try:
            json = resp.json()
        except Exception:
            json = None

        try:
            resp.raise_for_status()
            return json[0]
        except requests.HTTPError:
            if isinstance(json, dict) and 'message' in json:
                if json['message'] == "Insufficient membership":
                    raise OwnershipError(json['message'])
                else:
                    raise AuthError(json['message'])
            else:
                raise 
Example #27
Source File: action.py    From insightconnect-plugins with MIT License 6 votes vote down vote up
def run(self, params={}):
        name = params.get("name")
        q = params.get("q")
        offset = params.get("offset")
        limit = params.get("limit")

        params = dict()
        if name is not None:
            params["name"] = name
        if q is not None:
            params["q"] = q
        params["offset"] = offset
        params["limit"] = limit

        try:
            response = self.connection.CLIENT.get(self.__URL, params=params)
            entries = response.json()["items"]
            entries = komand.helper.clean(entries)
        except (requests.ConnectionError, requests.HTTPError, KeyError, ValueError) as error:
            raise error
        return {"entries": entries} 
Example #28
Source File: probe_search.py    From ripe-atlas-tools with GNU General Public License v3.0 6 votes vote down vote up
def test_location_google_breaks(self):
        """User passed location arg but google api gave error"""
        caught_exceptions = [
            requests.ConnectionError, requests.HTTPError, requests.Timeout]
        with mock.patch('requests.get') as mock_get:
            for exception in caught_exceptions:
                mock_get.side_effect = exception
                with capture_sys_output():
                    with self.assertRaises(RipeAtlasToolsException):
                        cmd = Command()
                        cmd.init_args(["--location", "blaaaa"])
                        cmd.run()
            mock_get.side_effect = Exception()
            with self.assertRaises(Exception):
                cmd = Command()
                cmd.init_args(["--location", "blaaaa"])
                cmd.run() 
Example #29
Source File: test_client.py    From Jike-Metro with MIT License 6 votes vote down vote up
def test_delete_my_post(self):
        mock_message = Mock()
        mock_message.type = 'ORIGINAL_POST'
        mock_message.id = '123'

        mock_response = Mock()
        mock_response.status_code = 200
        mock_response.json.return_value = {'success': True}
        mock_response.raise_for_status.return_value = None
        self.mock_jike_session.post.return_value = mock_response
        result = self.jike_client.delete_my_post(mock_message)
        self.assertTrue(result)
        # failed call by no post id provided
        with self.assertRaises(AssertionError):
            self.jike_client.delete_my_post(None)
        # failed call by server error
        mock_response.status_code = 403
        mock_response.raise_for_status.side_effect = requests.HTTPError()
        with self.assertRaises(requests.HTTPError):
            self.jike_client.delete_my_post(mock_message) 
Example #30
Source File: action.py    From insightconnect-plugins with MIT License 5 votes vote down vote up
def test(self):
        url = "https://api.cloudlock.com/api/v2/activities"
        try:
            response = self.connection.CLIENT.get(url)
        except (requests.ConnectionError, requests.HTTPError) as error:
            raise error
        return {}