SOAP (python)

Request w/ basic authentication (example)

notifier.py

import app.exc
from   app.generic import ag_log_exception
import logging
import requests

# Logger
logger = logging.getLogger()
logger.setLevel(logging.INFO)

""" Send SOAP request.
:param endpoint_url The webservice endpoint
:param body The SOAP request body
:param basic_user Username for basic authentication
:param basic_pass Password for basic authentication
:returns The SOAP response body
:throws AppSoapExc if status code different than 2xx
"""
def soap_request(endpoint_url, body, basic_user, basic_pass):
    method = "POST"
    url = endpoint_url

    payload = body.encode('utf-8')

    headers = {
        'Content-Type': "text/xml;charset=UTF-8",
        'SOAPAction': '""'
        }

    http_req = requests.Request(method, url, data=payload, headers=headers, auth=(basic_user, basic_pass))
    http_req_prepared = http_req.prepare()

    http_s = requests.Session()
    logger.info('INI soap_request Notificador: %s Request:\n%s', endpoint_url, payload)
    try:
        http_res = http_s.send(http_req_prepared)
        app.exc.AppSoapExc.raise_if_soap_error(http_res)
        logger.info('END soap_request Notificador: %d Response:\n%s', http_res.status_code, http_res.text)
        return http_res.text
    finally:
        http_res.close()