Raise http error python

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.

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) 
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
# 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:')
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)
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//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
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:
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")
"(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)
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
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. """

requests

Источник

Читайте также:  Default timezone asia in php
Оцените статью