How to use the requests.codes 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 kubeflow / kubeflow / testing / test_deploy.py View on Github external
],
              "network":
              "global/networks/default",
          },
      ],
  }
  request = instances.insert(project=args.project, zone=args.zone, body=body)
  response = None
  try:
    response = request.execute()
    print("done")
  except errors.HttpError as e:
    if not e.content:
      raise
    content = json.loads(e.content)
    if content.get("error", {}).get("code") == requests.codes.CONFLICT:
      # We don't want to keep going so we reraise the error after logging
      # a helpful error message.
      logging.error(
          "Either the VM or the disk %s already exists in zone "
          "%s in project %s ", args.vm_name, args.zone, args.project)
      raise
    else:
      raise

  op_id = response.get("name")
  final_op = vm_util.wait_for_operation(gce, args.project, args.zone, op_id)

  logging.info("Final result for insert operation: %s", final_op)
  if final_op.get("status") != "DONE":
    raise ValueError("Insert operation has status %s", final_op.get("status"))
github nicolas-carolo / hsploit / searcher / vulnerabilities / exploits / windows / local / 43857.py View on Github external
def send_request(body):
    url="http://localhost:16386/"
    headers = {"Content-Type": "text/xml; charset=utf-8", 'SOAPAction': '""', "Set-Cookie": "CCSessionID=SessionID11"}
    response = requests.post(url, data=body, headers=headers)
    if response.status_code != requests.codes.ok:
        print "Non-200 response. Exiting..."
        sys.exit()
    else:
        return response.text
github eyesoft / home-assistant-custom-components / min_renovasjon / __init__.py View on Github external
def _get_tommekalender_from_web_api(self):
        header = {CONST_KOMMUNE_NUMMER: self._kommunenr, CONST_APP_KEY: CONST_APP_KEY_VALUE}

        url = CONST_URL_TOMMEKALENDER
        url = url.replace('[gatenavn]', self.gatenavn)
        url = url.replace('[gatekode]', self.gatekode)
        url = url.replace('[husnr]', self.husnr)

        response = requests.get(url, headers=header)
        if response.status_code == requests.codes.ok:
            data = response.text
            return data
        else:
            _LOGGER.error(response.status_code)
            return None
github python / cherry-picker / cherry_picker / cherry_picker.py View on Github external
Create PR in GitHub
        """
        request_headers = sansio.create_headers(
            self.username, oauth_token=gh_auth)
        title, body = normalize_commit_message(commit_message)
        if not self.prefix_commit:
            title = f"[{base_branch}] {title}"
        data = {
          "title": title,
          "body": body,
          "head": f"{self.username}:{head_branch}",
          "base": base_branch,
          "maintainer_can_modify": True
        }
        response = requests.post(CPYTHON_CREATE_PR_URL, headers=request_headers, json=data)
        if response.status_code == requests.codes.created:
            click.echo(f"Backport PR created at {response.json()['html_url']}")
        else:
            click.echo(response.status_code)
            click.echo(response.text)
github morpheus65535 / bazarr / libs / apprise / plugins / NotifyTelegram.py View on Github external
self.bot_token,
            'getUpdates'
        )

        self.logger.debug(
            'Telegram User Detection POST URL: %s (cert_verify=%r)' % (
                url, self.verify_certificate))

        try:
            r = requests.post(
                url,
                headers=headers,
                verify=self.verify_certificate,
            )

            if r.status_code != requests.codes.ok:
                # We had a problem
                status_str = \
                    NotifyTelegram.http_response_code_lookup(r.status_code)

                try:
                    # Try to get the error message if we can:
                    error_msg = loads(r.content)['description']

                except Exception:
                    error_msg = None

                if error_msg:
                    self.logger.warning(
                        'Failed to detect the Telegram user: (%s) %s.' % (
                            r.status_code, error_msg))
github pubnub / python / pubnub / request_handlers / requests_handler.py View on Github external
if 'uuid' in query and len(query['uuid']) > 0:
                uuid = query['uuid'][0]

            if 'auth_key' in query and len(query['auth_key']) > 0:
                auth_key = query['auth_key'][0]

            response_info = ResponseInfo(
                status_code=res.status_code,
                tls_enabled='https' == url.scheme,
                origin=url.hostname,
                uuid=uuid,
                auth_key=auth_key,
                client_request=res.request
            )

        if res.status_code != requests.codes.ok:
            if res.status_code == 403:
                status_category = PNStatusCategory.PNAccessDeniedCategory

            if res.status_code == 400:
                status_category = PNStatusCategory.PNBadRequestCategory

            if res.text is None:
                text = "N/A"
            else:
                text = res.text

            if res.status_code >= 500:
                err = PNERR_SERVER_ERROR
            else:
                err = PNERR_CLIENT_ERROR
            try:
github SQiShER / ansible-modules-couchdb / lib / couchdb_user.py View on Github external
def get_document(self, database, document_id):
        url = self._get_absolute_url("/{0}/{1}".format(database, document_id))
        headers = {"Accept": "application/json"}
        r = requests.get(url, headers=headers, auth=self._auth)
        if r.status_code in [requests.codes.ok, requests.codes.not_modified]:
            return r.json()
        elif r.status_code == requests.codes.not_found:
            return None
        else:
            raise self._create_exception(r)
github JBEI / edd / jbei / rest / clients / edd / api.py View on Github external
query_url = kwargs.get(_QUERY_URL_PARAM, None)
        if query_url:
            response = self.session.get(query_url, headers=self._json_header)
        else:
            search_params = {}
            _set_if_value_valid(search_params, UNIT_NAME_REGEX_PARAM,
                                kwargs.pop('unit_name_regex', None))
            _set_if_value_valid(search_params, PAGE_NUMBER_URL_PARAM,
                                kwargs.pop(_PAGE_NUMBER_PARAM, None))

            # make the HTTP request
            url = '%s/rest/measurement_units/' % self.base_url
            response = self.session.get(url, params=search_params, headers=self._json_header)

        # throw an error for unexpected reply
        if response.status_code != requests.codes.ok:
            response.raise_for_status()

        return DrfPagedResult.of(response.text, model_class=MeasurementUnit)
github wikimedia / pywikibot / scripts / reflinks.py View on Github external
if redir != ref.link and \
                       domain.findall(redir) == domain.findall(link):
                        if soft404.search(redir) and \
                           not soft404.search(ref.link):
                            pywikibot.output(color_format(
                                '{lightyellow}WARNING{default} : '
                                'Redirect 404 : {0} ', ref.link))
                            continue
                        if dirIndex.match(redir) and \
                           not dirIndex.match(ref.link):
                            pywikibot.output(color_format(
                                '{lightyellow}WARNING{default} : '
                                'Redirect to root : {0} ', ref.link))
                            continue

                    if f.status != requests.codes.ok:
                        pywikibot.output('HTTP error ({0}) for {1} on {2}'
                                         .format(f.status, ref.url,
                                                 page.title(as_link=True)),
                                         toStdout=True)
                        # 410 Gone, indicates that the resource has been
                        # purposely removed
                        if f.status == 410 or \
                           (f.status == 404 and ('\t{}\t'.format(ref.url)
                                                 in dead_links)):
                            repl = ref.refDead()
                            new_text = new_text.replace(match.group(), repl)
                        continue

                    linkedpagetext = f.raw
                except UnicodeError:
                    # example:
github caronc / apprise / apprise / plugins / NotifyMessageBird.py View on Github external
#       }
                #     ]
                #   },
                #   "validity": null,
                #   "gateway": 10,
                #   "typeDetails": {},
                #   "href": "https://rest.messagebird.com/messages/\
                #       b5d424244a5b4fd0b5b5728bccaafc23",
                #   "datacoding": "plain",
                #   "scheduledDatetime": null,
                #   "type": "sms",
                #   "id": "b5d424244a5b4fd0b5b5728bccaafc23"
                # }

                if r.status_code not in (
                        requests.codes.ok, requests.codes.created):
                    # We had a problem
                    status_str = \
                        NotifyMessageBird.http_response_code_lookup(
                            r.status_code)

                    self.logger.warning(
                        'Failed to send MessageBird notification to {}: '
                        '{}{}error={}.'.format(
                            ','.join(target),
                            status_str,
                            ', ' if status_str else '',
                            r.status_code))

                    self.logger.debug(
                        'Response Details:\r\n{}'.format(r.content))