How to use the requests.exceptions.HTTPError function in requests

To help you get started, we’ve selected a few requests examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github kmyk / online-judge-tools / tests / command_submit.py View on Github external
int a; cin >> a;
            int b, c; cin >> b >> c;
            string s; cin >> s;
            cout << a + b + c << ' ' << s << endl;
            return 0;
        }
        '''
        files = [
            {
                'path': 'main.cpp',
                'data': code
            },
        ]

        with tests.utils.sandbox(files):
            with self.assertRaises(requests.exceptions.HTTPError):
                args = ["submit", '-y', '--no-open', url, 'main.cpp']
                args = get_parser().parse_args(args=args)
                submit(args)
github OriginProtocol / origin / origin-bridge / logic / attestation_service.py View on Github external
params = {
            'country_code': country_calling_code,
            'phone_number': phone,
            'verification_code': code
        }

        headers = {
            'X-Authy-API-Key': settings.TWILIO_VERIFY_API_KEY
        }

        url = 'https://api.authy.com/protected/json/phones/verification/check'
        response = requests.get(url, params=params, headers=headers)

        try:
            response.raise_for_status()
        except requests.exceptions.HTTPError as exc:
            logger.exception(exc)
            if response.json()['error_code'] == '60023':
                # This error code could also mean that no phone verification was ever
                # created for that country calling code and phone number
                raise ValidationError('Verification code has expired.',
                                      field_names=['code'])
            elif response.json()['error_code'] == '60022':
                raise ValidationError('Verification code is incorrect.',
                                      field_names=['code'])
            else:
                raise PhoneVerificationError(
                    'Could not verify code. Please try again shortly.'
                )

        # This may be unnecessary because the response has a 200 status code
        # but it a good precaution to handle any inconsistency between the
github couchbaselabs / mobile-testkit / testsuites / CBLTester / CBL_Functional_tests / TestSetup_FunctionalTests / test_no_conflicts_cbl.py View on Github external
# Start and stop continuous replication
    replicator = Replication(base_url)
    authenticator = Authenticator(base_url)
    replicator_authenticator = authenticator.authentication(session_id, cookie, authentication_type="session")
    repl_config = replicator.configure(cbl_db, sg_blip_url, continuous=True, channels=channels, replicator_authenticator=replicator_authenticator)
    repl = replicator.create(repl_config)
    replicator.start(repl)
    replicator.wait_until_replicator_idle(repl)
    total = replicator.getTotal(repl)
    completed = replicator.getCompleted(repl)
    replicator.stop(repl)
    assert total == completed, "total is not equal to completed"
    sg_docs = sg_client.get_all_docs(url=sg_url, db=sg_db, auth=session)

    for doc in sg_docs["rows"]:
        with pytest.raises(HTTPError) as he:
            sg_client.add_conflict(url=sg_url, db=sg_db, doc_id=doc["id"], parent_revisions=doc["value"]["rev"], new_revision="2-foo",
                                   auth=session)
        assert he.value.message.startswith('409 Client Error: Conflict for url:')
github thisbejim / Pyrebase / pyrebase / pyrebase.py View on Github external
def raise_detailed_error(request_object):
    try:
        request_object.raise_for_status()
    except HTTPError as e:
        # raise detailed error message
        # TODO: Check if we get a { "error" : "Permission denied." } and handle automatically
        raise HTTPError(e, request_object.text)
github AnalogJ / lexicon / lexicon / providers / conoha.py View on Github external
def _create_record(self, rtype, name, content):
        if not rtype:
            raise Exception("rtype must be specified.")
        if not name:
            raise Exception("name must be specified.")
        if not content:
            raise Exception("content must be specified.")
        if not self._get_lexicon_option("priority") and rtype in ("MX", "SRV"):
            raise Exception("priority must be specified.")

        try:
            self._post(
                "/domains/{0}/records".format(self.domain_id),
                self._record_payload(rtype, name, content),
            )
        except requests.exceptions.HTTPError as err:
            # 409 Duplicate Record
            if err.response.status_code != 409:
                raise err

        LOGGER.debug("create_record: %s", True)
        return True
github mozilla / code-review / bot / code_review_bot / __init__.py View on Github external
def build_hash(self):
        """
        Build a uniquely identifying hash for that issue
        """
        assert self.revision is not None, "Missing revision"

        try:
            # Load all the lines affected by the issue
            file_content = self.revision.load_file(self.path)
        except requests.exceptions.HTTPError as e:
            if e.response.status_code == 404:
                logger.warning(
                    "Failed to download a file with an issue", path=self.path
                )

                # We still build the hash with empty content
                file_content = ""
            else:
                # When encountering another HTTP error, raise the issue
                raise

        # Build raw content:
        # 1. lines affected by patch
        # 2. without any spaces around each line
        file_lines = file_content.splitlines()
        if self.line is None or self.nb_lines is None:
github vmware / tern / tern / analyze / docker / container.py View on Github external
def start_container(image_tag_string):
    '''Start the test container in detach state'''
    try:
        client.containers.run(image_tag_string, name=container, detach=True)
    except requests.exceptions.HTTPError:
        # container may already be running
        pass
    try:
        remove_container()
        client.containers.run(image_tag_string, name=container, detach=True)
    except requests.exceptions.HTTPError:
        # not sure what the error is now
        raise Exception("Cannot remove running container")
github SIlver-- / asoiafsearchbot-reddit / asoiaf-reddit.py View on Github external
"(http://www.reddit.com/r/asoiaf/comments/25amke/"
                    "spoilers_all_introducing_asoiafsearchbot_command/) | "
                    "[^([Practice Thread])]"
                    "(http://www.reddit.com/r/asoiaf/comments/26ez9u/"
                    "spoilers_all_asoiafsearchbot_practice_thread/) | "
                    "[^([Suggestions])]"
                    "(http://www.reddit.com/message/compose/?to=RemindMeBotWrangler&subject=Suggestion) | "
                    "[^([Code])]"
                    "(https://github.com/SIlver--/asoiafsearchbot-reddit)"

                )
            
            print self._commentUser
            #self.comment.reply(self._commentUser)

        except (HTTPError, ConnectionError, Timeout, timeout) as err:
            print err
        except RateLimitExceeded as err:
            print err
            time.sleep(10)
        except APIException as err: # Catch any less specific API errors
            print err
        else:
            self.commented.append(self.comment.id)
github sushant354 / egazette / iasync.py View on Github external
def ia_upload(self, identifier, metadata, to_upload, files, rawfile):
        success = False
        try: 
            if metadata:
                r = upload(identifier, to_upload, metadata = metadata, \
                           access_key = self.access_key, \
                           secret_key = self.secret_key, \
                           retries=100)
            else:               
                r = upload(identifier, to_upload, \
                           access_key = self.access_key, \
                           secret_key = self.secret_key, \
                           retries=100)
            success = True
        except HTTPError as e:
           self.logger.warn('Error in upload for %s: %s', identifier, e)
           msg = '%s' % e
           if re.search('Syntax error detected in pdf data', msg) or \
                  re.search('error checking pdf file', msg):
              r = self.upload_bad_pdf(identifier, rawfile, files)
              success = True

        except Exception as e:
           self.logger.warn('Error in upload for %s: %s', identifier, e)
           success = False
        return success
github hozn / stravalib / stravalib / exc.py View on Github external
pass


class LoginRequired(AuthError):
    """
    Login is required to perform specified action.
    """


class UnboundEntity(RuntimeError):
    """
    Exception used to indicate that a model Entity is not bound to client instances.
    """


class Fault(requests.exceptions.HTTPError):
    """
    Container for exceptions raised by the remote server.
    """


class ObjectNotFound(Fault):
    """
    When we get a 404 back from an API call.
    """


class AccessUnauthorized(Fault):
    """
    When we get a 401 back from an API call.
    """