Python requests.codes() Examples

The following are 23 code examples of requests.codes(). 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: vault_key_manager.py    From castellan with Apache License 2.0 8 votes vote down vote up
def _do_http_request(self, method, resource, json=None):
        verify = self._verify_server
        headers = self._build_auth_headers()

        try:
            resp = method(resource, headers=headers, json=json, verify=verify)
        except requests.exceptions.Timeout as ex:
            raise exception.KeyManagerError(str(ex))
        except requests.exceptions.ConnectionError as ex:
            raise exception.KeyManagerError(str(ex))
        except Exception as ex:
            raise exception.KeyManagerError(str(ex))

        if resp.status_code in _EXCEPTIONS_BY_CODE:
            raise exception.KeyManagerError(resp.reason)
        if resp.status_code == requests.codes['forbidden']:
            raise exception.Forbidden()

        return resp 
Example #2
Source File: api_octopart.py    From KiCost with MIT License 6 votes vote down vote up
def query(query, apiKey=None):
        """Send query to Octopart and return results."""
        #url = 'http://octopart.com/api/v3/parts/match'
        #payload = {'queries': json.dumps(query), 'include\[\]': 'specs', 'apikey': token}
        #response = requests.get(url, params=payload)
        if apiKey:
            url = 'http://octopart.com/api/v3/parts/match?queries=%s' \
            % json.dumps(query)
            url += '&apikey=' + apiKey
        else:
            url = 'https://temp-octopart-proxy.kitspace.org/parts/match?queries=%s' \
            % json.dumps(query)
        url += '&include[]=specs'
        url += '&include[]=datasheets'
        response = requests.get(url)
        if response.status_code == requests.codes['ok']:
            results = json.loads(response.text).get('results')
            return results
        elif response.status_code == requests.codes['not_found']: #404
            raise Exception('Octopart server not found.')
        elif response.status_code == 403:
            raise Exception('Octopart KEY invalid, registre one at "https://www.octopart.com".')
        else:
            raise Exception('Octopart error: ' + str(response.status_code)) 
Example #3
Source File: __init__.py    From uqcsbot with MIT License 6 votes vote down vote up
def get_user_info(user_id):
    """
    Returns info about a user

    See https://api.slack.com/methods/users.info for the contents of info
    """
    api_url = 'https://slack.com/api/users.info'
    response = requests.get(api_url, params={'token': UQCSTESTING_USER_TOKEN, 'user': user_id})

    if response.status_code != requests.codes['ok']:
        LOGGER.error(f'Received status code {response.status.code}')
        sys.exit(1)

    json_contents = json.loads(response.content)
    if not json_contents['ok']:
        LOGGER.error(json_contents['error'])
        sys.exit(1)

    return json_contents 
Example #4
Source File: __init__.py    From uqcsbot with MIT License 5 votes vote down vote up
def is_bot_avaliable(user_id):
    """
    Returns true if the given user_id is an active bot that is available (i.e. is
    not currently 'active' which would mean it is in use by another user).
    """

    api_url = 'https://slack.com/api/users.getPresence'
    response = requests.get(api_url, params={'token': UQCSTESTING_USER_TOKEN, 'user': user_id})
    if response.status_code != requests.codes['ok']:
        return False

    json_contents = json.loads(response.content)
    return json_contents['ok'] and json_contents['presence'] == 'away' 
Example #5
Source File: autenticacion.py    From python-cfdiclient with GNU General Public License v3.0 5 votes vote down vote up
def obtener_token(self, id=uuid.uuid4()):
        
        soapreq = self.__generar_soapreq__(id)

        headers = {
            'Content-type': 'text/xml;charset="utf-8"',
            'Accept': 'text/xml',
            'Cache-Control': 'no-cache',
            'SOAPAction': self.SOAP_ACTION
        }

        response = requests.post(self.SOAP_URL, data=soapreq, headers=headers, verify=True)

        if response.status_code != requests.codes['ok']:
            if not response.text.startswith('<s:Envelope'):
                ex = 'El webservice Autenticacion responde: {}'.format(response.text)
            else:
                resp_xml = etree.fromstring(response.text)
                ex = resp_xml.find('s:Body/s:Fault/faultstring', namespaces=self.NSMAP).text
            raise Exception(ex)

        if not response.text.startswith('<s:Envelope'):
            ex = 'El webservice Autenticacion responde: {}'.format(response.text)
            raise Exception(ex)

        nsmap= {
            's': 'http://schemas.xmlsoap.org/soap/envelope/',
            None: 'http://DescargaMasivaTerceros.gob.mx'
        }

        resp_xml = etree.fromstring(response.text)

        token = resp_xml.find('s:Body/AutenticaResponse/AutenticaResult', namespaces=nsmap)

        return token.text 
Example #6
Source File: api_partinfo_kitspace.py    From KiCost with MIT License 5 votes vote down vote up
def query(query_parts, distributors, query_type=QUERY_MATCH):
        '''Send query to server and return results.'''
        
        ##TODO this `dist_xlate` have to be better coded into this file.
        dist_xlate = distributors_modules_dict['api_partinfo_kitspace']['dist_translation']
        def find_key(input_dict, value):
            return next((k for k, v in input_dict.items() if v == value), None)
        distributors = ([find_key(dist_xlate, d) for d in distributors])
        
        query_type = re.sub('\{DISTRIBUTORS\}', '["'+ '","'.join(distributors) +'"]' , query_type)
        #r = requests.post(QUERY_URL, {"query": QUERY_SEARCH, "variables": variables}) #TODO future use for ISSUE #17
        variables = re.sub('\'', '\"', str(query_parts))
        variables = re.sub('\s', '', variables)
        # Python 2 prepends a 'u' before the query strings and this makes PartInfo
        # complain, so remove them.
        variables = re.sub(':u"', ':"', variables)
        variables = re.sub('{u"', '{"', variables)
        variables = '{{"input":{}}}'.format(variables)
        response = requests.post(QUERY_URL, {'query': query_type, "variables": variables})
        if response.status_code == requests.codes['ok']: #200
            results = json.loads(response.text)
            return results
        elif response.status_code == requests.codes['not_found']: #404
            raise Exception('Kitspace server not found check your internet connection.')
        elif response.status_code == requests.codes['request_timeout']: #408
            raise Exception('KitSpace is not responding.')
        elif response.status_code == requests.codes['bad_request']: #400
            raise Exception('Bad request to Kitspace server probably due to an incorrect string format check your `manf#` codes and contact the suport team.')
        elif response.status_code == requests.codes['gateway_timeout']: # 504
            raise Exception('One of the internal Kitspace services may experiencing problems. Contact the Kitspace support.')
        else:
            raise Exception('Kitspace error: ' + str(response.status_code)) 
Example #7
Source File: defaultstt.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def transcribe(self, fp):
        sttHeaders = {'Authorization': 'Bearer %s' % self.key,
                      'accept': 'application/json',
                      'Content-Type': 'audio/wav'}

        audio = fp.read()
        sttData = requests.post('https://api.wit.ai/speech?v=20170307',
                          data=audio,
                          headers=sttHeaders)

        try:
            sttData.raise_for_status()
        except requests.exceptions.HTTPError:
            self._logger.critical('Request failed with http status %d',
                                  sttData.status_code)
            return []
            if sttData.status_code == requests.codes['forbidden']:
                self._logger.warning('Request forbidden, check your API key')
            return []

        try:
            sttResponse = sttData.json()['_text']
            if len(sttResponse) == 0:
                raise ValueError('Nothing transcribed.')
        except ValueError as e:
            self._logger.warning('Empty response: %s', e.args[0])
            results = []
        except (KeyError, IndexError):
            self._logger.warning('Cannot parse response.', exc_info=True)
            results = []
        else:
            results = [sttResponse.upper()]
            self._logger.info('Transcribed: %r', results)
        return results 
Example #8
Source File: __init__.py    From OctoPrint-Enclosure with GNU General Public License v3.0 5 votes vote down vote up
def send_notification(self, message):
        try:
            provider = self._settings.get(["notification_provider"])
            if provider == 'ifttt':
                event = self._settings.get(["notification_event_name"])
                api_key = self._settings.get(["notification_api_key"])
                self._logger.debug("Sending notification to: %s with msg: %s with key: %s", provider, message,
                        api_key)
                try:
                    res = self.ifttt_notification(message, event, api_key)
                except requests.exceptions.ConnectionError:
                    self._logger.info("Error: Could not connect to IFTTT")
                except requests.exceptions.HTTPError:
                    self._logger.info("Error: Received invalid response")
                except requests.exceptions.Timeout:
                    self._logger.info("Error: Request timed out")
                except requests.exceptions.TooManyRedirects:
                    self._logger.info("Error: Too many redirects")
                except requests.exceptions.RequestException as reqe:
                    self._logger.info("Error: {e}".format(e=reqe))
                if res.status_code != requests.codes['ok']:
                    try:
                        j = res.json()
                    except ValueError:
                        self._logger.info('Error: Could not parse server response. Event not sent')
                    for err in j['errors']:
                        self._logger.info('Error: {}'.format(err['message']))
        except Exception as ex:
            self.log_error(ex)
            pass 
Example #9
Source File: __init__.py    From uqcsbot with MIT License 5 votes vote down vote up
def get_free_test_bot():
    """
    Pings a channel on the UQCSTesting Slack that contains all the available
    bots, and Mitch. We can poll this channel to find  bots which are 'away'
    (that is, not currently being used by anyone else)

    Returns info about the bot

    See https://api.slack.com/methods/users.info for the contents of info
    """
    api_url = 'https://slack.com/api/conversations.members'
    response = requests.get(api_url, params={'token': UQCSTESTING_USER_TOKEN,
                                             'channel': SECRET_BOT_MEETING_ROOM})
    if response.status_code != requests.codes['ok']:
        LOGGER.error(f'Received status code {response.status.code}')
        sys.exit(1)

    json_contents = json.loads(response.content)
    if not json_contents['ok']:
        LOGGER.error(json_contents['error'])
        sys.exit(1)

    for user_id in json_contents['members']:
        info = get_user_info(user_id)
        if is_active_bot(info) and is_bot_avaliable(user_id):
            return info
    return None 
Example #10
Source File: mal.py    From mangaki with GNU Affero General Public License v3.0 5 votes vote down vote up
def _translate_http_exceptions(resp: requests.Response) -> None:
        if resp.status_code == requests.codes['FORBIDDEN']:
            raise RuntimeError('Invalid MAL credentials!')

        if not resp.status_code == requests.codes['ALL_GOOD']:
            raise RuntimeError('MAL request failure!') 
Example #11
Source File: http.py    From plex-for-kodi with GNU General Public License v2.0 5 votes vote down vote up
def wasNotFound(self):
        return self.currentResponse is not None and self.currentResponse.status_code == requests.codes.not_found 
Example #12
Source File: __init__.py    From IOTA_demo with MIT License 5 votes vote down vote up
def send_request(self, payload, **kwargs):
    # type: (dict, dict) -> dict
    kwargs.setdefault('headers', {})
    for key, value in iteritems(self.DEFAULT_HEADERS):
      kwargs['headers'].setdefault(key, value)

    response = self._send_http_request(
      # Use a custom JSON encoder that knows how to convert Tryte values.
      payload = JsonEncoder().encode(payload),

      url = self.node_url,
      **kwargs
    )

    return self._interpret_response(response, payload, {codes['ok']}) 
Example #13
Source File: vault_key_manager.py    From castellan with Apache License 2.0 5 votes vote down vote up
def list(self, context, object_type=None, metadata_only=False):
        """Lists the managed objects given the criteria."""

        if object_type and object_type not in self._secret_type_dict:
            msg = _("Invalid secret type: %s") % object_type
            raise exception.KeyManagerError(reason=msg)

        resp = self._do_http_request(self._session.get,
                                     self._get_resource_url())

        if resp.status_code == requests.codes['not_found']:
            keys = []
        else:
            keys = resp.json()['data']['keys']

        objects = []
        for obj_id in keys:
            try:
                obj = self.get(context, obj_id, metadata_only=metadata_only)
                if object_type is None or isinstance(obj, object_type):
                    objects.append(obj)
            except exception.ManagedObjectNotFoundError as e:
                LOG.warning("Error occurred while retrieving object "
                            "metadata, not adding it to the list: %s", e)
                pass
        return objects 
Example #14
Source File: vault_key_manager.py    From castellan with Apache License 2.0 5 votes vote down vote up
def delete(self, context, key_id):
        """Represents deleting the key."""

        if not key_id:
            raise exception.KeyManagerError('key identifier not provided')

        resp = self._do_http_request(self._session.delete,
                                     self._get_resource_url(key_id))

        if resp.status_code == requests.codes['not_found']:
            raise exception.ManagedObjectNotFoundError(uuid=key_id) 
Example #15
Source File: vault_key_manager.py    From castellan with Apache License 2.0 5 votes vote down vote up
def get(self, context, key_id, metadata_only=False):
        """Retrieves the key identified by the specified id."""

        if not key_id:
            raise exception.KeyManagerError('key identifier not provided')

        resp = self._do_http_request(self._session.get,
                                     self._get_resource_url(key_id))

        if resp.status_code == requests.codes['not_found']:
            raise exception.ManagedObjectNotFoundError(uuid=key_id)

        record = resp.json()['data']
        if self._kv_version > 1:
            record = record['data']

        key = None if metadata_only else binascii.unhexlify(record['value'])

        clazz = None
        for type_clazz, type_name in self._secret_type_dict.items():
            if type_name == record['type']:
                clazz = type_clazz

        if clazz is None:
            raise exception.KeyManagerError(
                "Unknown type : %r" % record['type'])

        if hasattr(clazz, 'algorithm') and hasattr(clazz, 'bit_length'):
            return clazz(record['algorithm'],
                         record['bit_length'],
                         key,
                         record['name'],
                         record['created'],
                         key_id)
        else:
            return clazz(key,
                         record['name'],
                         record['created'],
                         key_id) 
Example #16
Source File: jsonrpc.py    From manila with Apache License 2.0 4 votes vote down vote up
def call(self, method_name, user_parameters, expected_errors=None):
        if expected_errors is None:
            expected_errors = []
        # prepare request
        self._id += 1
        parameters = {'retry': 'INFINITELY'}  # Backend specific setting
        if user_parameters:
            parameters.update(user_parameters)
        post_data = {
            'jsonrpc': '2.0',
            'method': method_name,
            'params': parameters,
            'id': six.text_type(self._id),
        }
        LOG.debug("Request payload to be send is: %s",
                  jsonutils.dumps(post_data))

        # send request
        if self._url_scheme == 'https':
            if self._cert_file:
                result = requests.post(url=self._url,
                                       json=post_data,
                                       auth=self._credentials,
                                       verify=self._ca_file,
                                       cert=(self._cert_file, self._key_file))
            else:
                result = requests.post(url=self._url,
                                       json=post_data,
                                       auth=self._credentials,
                                       verify=self._ca_file)
        else:
            result = requests.post(url=self._url,
                                   json=post_data,
                                   auth=self._credentials)

        # eval request response
        if result.status_code == codes['OK']:
            LOG.debug("Retrieved data from Quobyte backend: %s", result.text)
            response = result.json()
            return self._checked_for_application_error(response,
                                                       expected_errors)

        # If things did not work out provide error info
        LOG.debug("Backend request resulted in error: %s", result.text)
        result.raise_for_status() 
Example #17
Source File: vault_key_manager.py    From castellan with Apache License 2.0 4 votes vote down vote up
def _build_auth_headers(self):
        if self._root_token_id:
            return {'X-Vault-Token': self._root_token_id}

        if self._approle_token_id:
            return {'X-Vault-Token': self._approle_token_id}

        if self._approle_role_id:
            params = {
                'role_id': self._approle_role_id
            }
            if self._approle_secret_id:
                params['secret_id'] = self._approle_secret_id
            approle_login_url = '{}v1/auth/approle/login'.format(
                self._get_url()
            )
            token_issue_utc = timeutils.utcnow()
            try:
                resp = self._session.post(url=approle_login_url,
                                          json=params,
                                          verify=self._verify_server)
            except requests.exceptions.Timeout as ex:
                raise exception.KeyManagerError(str(ex))
            except requests.exceptions.ConnectionError as ex:
                raise exception.KeyManagerError(str(ex))
            except Exception as ex:
                raise exception.KeyManagerError(str(ex))

            if resp.status_code in _EXCEPTIONS_BY_CODE:
                raise exception.KeyManagerError(resp.reason)
            if resp.status_code == requests.codes['forbidden']:
                raise exception.Forbidden()

            resp_data = resp.json()

            if resp.status_code == requests.codes['bad_request']:
                raise exception.KeyManagerError(', '.join(resp_data['errors']))

            self._cached_approle_token_id = resp_data['auth']['client_token']
            self._approle_token_issue = token_issue_utc
            self._approle_token_ttl = resp_data['auth']['lease_duration']
            return {'X-Vault-Token': self._approle_token_id}

        return {} 
Example #18
Source File: instadeploy.py    From cf-mendix-buildpack with Apache License 2.0 4 votes vote down vote up
def build():
    mpr = os.path.abspath(util.get_mpr_file_from_dir(PROJECT_DIR))
    response = requests.post(
        "http://localhost:6666/build",
        data=json.dumps(
            {
                "target": "Deploy",
                "projectFilePath": mpr,
                "forceFullDeployment": False,
            }
        ),
        headers={"Content-Type": "application/json"},
        timeout=120,
    )

    if response.status_code != requests.codes["ok"]:
        raise MxBuildFailure(
            "MxBuild failure", response.status_code, response.json()
        )

    result = response.json()
    if result["status"] == "Success":
        try:
            sync_project_files()
            logging.info("Syncing project files ...")
        except Exception:
            logging.warning(
                "Syncing project files failed: %s", traceback.format_exc()
            )
            raise
        try:
            send_metadata_to_cloudportal()
        except Exception:
            logging.warning(
                "Failed to send instadeploy feedback to Cloud Portal",
                exc_info=True,
            )
    else:
        logging.warning(
            "Not syncing project files. MxBuild result: %s", result
        )

    return result 
Example #19
Source File: system_entity_recognizer.py    From mindmeld with Apache License 2.0 4 votes vote down vote up
def get_response(self, data):
        """
        Send a post request to Duckling, data is a dictionary with field `text`.
        Return a tuple consisting the JSON response and a response code.

        Args:
            data (dict)

        Returns:
            (dict, int)
        """
        try:
            response = requests.request(
                "POST", self.url, data=data, timeout=float(SYS_ENTITY_REQUEST_TIMEOUT)
            )

            if response.status_code == requests.codes["ok"]:
                response_json = response.json()

                # Remove the redundant 'values' key in the response['value'] dictionary
                for i, entity_dict in enumerate(response_json):
                    if "values" in entity_dict["value"]:
                        del response_json[i]["value"]["values"]

                return response_json, response.status_code
            else:
                raise SystemEntityError("System entity status code is not 200.")
        except requests.ConnectionError:
            sys.exit(
                "Unable to connect to the system entity recognizer. Make sure it's "
                "running by typing 'mindmeld num-parse' at the command line."
            )
        except Exception as ex:  # pylint: disable=broad-except
            logger.error(
                "Numerical Entity Recognizer Error: %s\nURL: %r\nData: %s",
                ex,
                self.url,
                json.dumps(data),
            )
            sys.exit(
                "\nThe system entity recognizer encountered the following "
                + "error:\n"
                + str(ex)
                + "\nURL: "
                + self.url
                + "\nRaw data: "
                + str(data)
                + "\nPlease check your data and ensure Numerical parsing service is running. "
                "Make sure it's running by typing "
                "'mindmeld num-parse' at the command line."
            ) 
Example #20
Source File: solicitadescarga.py    From python-cfdiclient with GNU General Public License v3.0 4 votes vote down vote up
def solicitar_descarga(
            self, token, rfc_solicitante, fecha_inicial, fecha_final,
            rfc_emisor=None, rfc_receptor=None, tipo_solicitud='CFDI'
        ):
        
        soapreq = self.__generar_soapreq__(
            rfc_solicitante, fecha_inicial, fecha_final, rfc_emisor, rfc_receptor, tipo_solicitud
        )

        headers = {
            'Content-type': 'text/xml;charset="utf-8"',
            'Accept': 'text/xml',
            'Cache-Control': 'no-cache',
            'SOAPAction': self.SOAP_ACTION,
            'Authorization': 'WRAP access_token="{}"'.format(token)
        }

        response = requests.post(self.SOAP_URL, data=soapreq, headers=headers, verify=True)

        if response.status_code != requests.codes['ok']:
            if not response.text.startswith('<s:Envelope'):
                ex = 'El webservice Autenticacion responde: {}'.format(response.text)
            else:
                resp_xml = etree.fromstring(response.text)
                ex = resp_xml.find('s:Body/s:Fault/faultstring', namespaces=self.NSMAP).text
            raise Exception(ex)

        if not response.text.startswith('<s:Envelope'):
            ex = 'El webservice Autenticacion responde: {}'.format(response.text)
            raise Exception(ex)

        nsmap= {
            's': 'http://schemas.xmlsoap.org/soap/envelope/',
            None: 'http://DescargaMasivaTerceros.sat.gob.mx'
        }

        resp_xml = etree.fromstring(response.text)

        f_val = 's:Body/SolicitaDescargaResponse/SolicitaDescargaResult'

        s_d_r = resp_xml.find(f_val, namespaces=nsmap)

        ret_val = {
            'id_solicitud': s_d_r.get('IdSolicitud'),
            'cod_estatus': s_d_r.get('CodEstatus'),
            'mensaje': s_d_r.get('Mensaje')
        }

        return ret_val 
Example #21
Source File: descargamasiva.py    From python-cfdiclient with GNU General Public License v3.0 4 votes vote down vote up
def descargar_paquete(self, token, rfc_solicitante, id_paquete):
        
        soapreq = self.__generar_soapreq__(rfc_solicitante, id_paquete)

        headers = {
            'Content-type': 'text/xml;charset="utf-8"',
            'Accept': 'text/xml',
            'Cache-Control': 'no-cache',
            'SOAPAction': self.SOAP_ACTION,
            'Authorization': 'WRAP access_token="{}"'.format(token)
        }

        response = requests.post(self.SOAP_URL, data=soapreq, headers=headers, verify=True)

        if response.status_code != requests.codes['ok']:
            if not response.text.startswith('<s:Envelope'):
                ex = 'El webservice Autenticacion responde: {}'.format(response.text)
            else:
                resp_xml = etree.fromstring(response.text)
                ex = resp_xml.find('s:Body/s:Fault/faultstring', namespaces=self.NSMAP).text
            raise Exception(ex)

        if not response.text.startswith('<s:Envelope'):
            ex = 'El webservice Autenticacion responde: {}'.format(response.text)
            raise Exception(ex)
        
        nsmap= {
            's': 'http://schemas.xmlsoap.org/soap/envelope/',
            'h': 'http://DescargaMasivaTerceros.sat.gob.mx',
            None: 'http://DescargaMasivaTerceros.sat.gob.mx'
        }

        resp_xml = etree.fromstring(response.text, parser=etree.XMLParser(huge_tree=True))

        respuesta = resp_xml.find('s:Header/h:respuesta', namespaces=nsmap)

        paquete = resp_xml.find('s:Body/RespuestaDescargaMasivaTercerosSalida/Paquete', namespaces=nsmap)

        ret_val = {
            'cod_estatus': respuesta.get('CodEstatus'),
            'mensaje': respuesta.get('Mensaje'),
            'paquete_b64': paquete.text,
        }

        return ret_val 
Example #22
Source File: verificasolicituddescarga.py    From python-cfdiclient with GNU General Public License v3.0 4 votes vote down vote up
def verificar_descarga(self, token, rfc_solicitante, id_solicitud):
        
        soapreq = self.__generar_soapreq__(rfc_solicitante, id_solicitud)

        headers = {
            'Content-type': 'text/xml;charset="utf-8"',
            'Accept': 'text/xml',
            'Cache-Control': 'no-cache',
            'SOAPAction': self.SOAP_ACTION,
            'Authorization': 'WRAP access_token="{}"'.format(token)
        }

        response = requests.post(self.SOAP_URL, data=soapreq, headers=headers, verify=True)

        if response.status_code != requests.codes['ok']:
            if not response.text.startswith('<s:Envelope'):
                ex = 'El webservice Autenticacion responde: {}'.format(response.text)
            else:
                resp_xml = etree.fromstring(response.text)
                ex = resp_xml.find('s:Body/s:Fault/faultstring', namespaces=self.NSMAP).text
            raise Exception(ex)

        if not response.text.startswith('<s:Envelope'):
            ex = 'El webservice Autenticacion responde: {}'.format(response.text)
            raise Exception(ex)

        nsmap= {
            's': 'http://schemas.xmlsoap.org/soap/envelope/',
            None: 'http://DescargaMasivaTerceros.sat.gob.mx'
        }

        resp_xml = etree.fromstring(response.text)

        f_val = 's:Body/VerificaSolicitudDescargaResponse/VerificaSolicitudDescargaResult'

        v_s_d_R = resp_xml.find(f_val, namespaces=nsmap)

        ret_val = {
            'cod_estatus': v_s_d_R.get('CodEstatus'),
            'estado_solicitud': v_s_d_R.get('EstadoSolicitud'),
            'codigo_estado_solicitud': v_s_d_R.get('CodigoEstadoSolicitud'),
            'numero_cfdis': v_s_d_R.get('NumeroCFDIs'),
            'mensaje': v_s_d_R.get('Mensaje'),
            'paquetes': []
        }

        for id_paquete in v_s_d_R.iter('{{{}}}IdsPaquetes'.format(nsmap[None])):
            ret_val['paquetes'].append(id_paquete.text)

        return ret_val 
Example #23
Source File: validacioncfdi.py    From python-cfdiclient with GNU General Public License v3.0 4 votes vote down vote up
def obtener_estado(self, rfc_emisor, rfc_receptor, total, uuid):
    soapreq = self.__generar_soapreq__(rfc_emisor, rfc_receptor, total, uuid)

    headers = {
        'Content-type': 'text/xml;charset="utf-8"',
        'Accept': 'text/xml',
        'Cache-Control': 'no-cache',
        'SOAPAction': self.SOAP_ACTION,
    }

    response = requests.post(self.SOAP_URL, data=soapreq, headers=headers, verify=True)


    if response.status_code != requests.codes['ok']:
        if not response.text.startswith('<s:Envelope'):
            ex = 'El webservice Autenticacion responde: {}'.format(response.text)
        else:
            resp_xml = etree.fromstring(response.text)
            ex = resp_xml.find('s:Body/s:Fault/faultstring', namespaces=self.NSMAP).text
        raise Exception(ex)

    if not response.text.startswith('<s:Envelope'):
        ex = 'El webservice Autenticacion responde: {}'.format(response.text)
        raise Exception(ex)

    nsmap = {
        's': 'http://schemas.xmlsoap.org/soap/envelope/',
        't': 'http://tempuri.org/',
        'a': 'http://schemas.datacontract.org/2004/07/Sat.Cfdi.Negocio.ConsultaCfdi.Servicio'
    }

    resp_xml = etree.fromstring(response.text)

    f_val = 's:Body/t:ConsultaResponse/t:ConsultaResult/a:CodigoEstatus'
    CodigoEstatus = resp_xml.find(f_val, namespaces=nsmap)

    f_val = 's:Body/t:ConsultaResponse/t:ConsultaResult/a:EsCancelable'
    EsCancelable = resp_xml.find(f_val, namespaces=nsmap)

    f_val = 's:Body/t:ConsultaResponse/t:ConsultaResult/a:Estado'
    Estado = resp_xml.find(f_val, namespaces=nsmap)

    ret_val = {
        'codigo_estatus': CodigoEstatus.text,
        'es_cancelable': EsCancelable.text,
        'estado': Estado.text
    }
    return ret_val