Exemple #1
0
    def execute(self, ssn):

        sessionconfig = ConfigObj(self.sessionconfigfile)

        for s in sessionconfig.sections:

            section = sessionconfig[s]
            url = "/".join([
                self.globalconfig["baseURL"], section["webservice"],
                section["webservicefile"]
            ])
            client = Client(url)
            client.set_options(soapheaders=ssn)

            for operation in section.sections:

                params = list(section[operation].values())
                paramlist = []

                inipos = client.__str__().find(operation) + len(operation) + 1
                endpos = client.__str__()[inipos:-1].find(" ") + inipos
                objecttype = client.__str__()[inipos:endpos]
                p = client.factory.create(objecttype)

                for param in params:
                    setattr(p, param[0], param[1])
                    paramlist.append(p)

                op = getattr(client.service, operation)
                result = op(paramlist)

                print(result)
Exemple #2
0
def form():
    name = request.args['userInput']
    times = request.args['times']
    hello_client = Client('http://localhost:7789/?wsdl')
    hello = hello_client.service.say_hello(name, times)
    data = Client.dict(hello)
    return render_template('result_soap.html', data=data, xml=hello_client.__str__())
Exemple #3
0
class BaseZuora(object):
    """
    SOAP Client based on Suds
    """
    def __init__(self,
                 wsdl,
                 username,
                 password,
                 session_duration=DEFAULT_SESSION_DURATION):
        self.wsdl = wsdl
        self.username = username
        self.password = password

        self.session = None
        self.session_duration = session_duration
        self.session_expiration = datetime.now()
        self.wsdl_path = 'file://%s' % os.path.abspath(self.wsdl)

        self.client = Client(self.wsdl_path,
                             transport=HttpTransportWithKeepAlive())

    def instanciate(self, instance_type_string):
        """
        Create object for client.factory.
        """
        return self.client.factory.create(instance_type_string)

    def set_session(self, session_id):
        """
        Record the session info.
        """
        self.session = session_id
        self.session_expiration = datetime.now() + timedelta(
            seconds=self.session_duration)
        session_namespace = ('ns1', 'http://api.zuora.com/')
        session = Element('session', ns=session_namespace).setText(session_id)
        header = Element('SessionHeader', ns=session_namespace)
        header.append(session)
        self.client.set_options(soapheaders=[header])

    def reset(self):
        """
        Reset the connection to the API.
        """
        self.session = None
        self.client.options.transport = HttpTransportWithKeepAlive()

    def call(self, method, *args, **kwargs):
        """
        Call a SOAP method.
        """
        if self.session is None or self.session_expiration >= datetime.now():
            self.login()

        try:
            response = method(*args, **kwargs)
            logger.info('Sent: %s', self.client.last_sent())
            logger.info('Received: %s', self.client.last_received())
            if isinstance(response, Text):  # Occasionally happens
                logger.warning('Invalid response %s, retrying...', response)
                self.reset()
                return self.call(method, *args, **kwargs)
        except WebFault as error:
            if error.fault.faultcode == 'fns:INVALID_SESSION':
                logger.warning('Invalid session, relogging...')
                self.reset()
                return self.call(method, *args, **kwargs)
            else:
                logger.info('Sent: %s', self.client.last_sent())
                logger.info('Received: %s', self.client.last_received())
                logger.error('WebFault: %s', error.__dict__)
                raise ZuoraException('WebFault: %s' % error.__dict__)
        except Exception as error:
            logger.info('Sent: %s', self.client.last_sent())
            logger.info('Received: %s', self.client.last_received())
            logger.error('Unexpected error: %s', error)
            raise ZuoraException('Unexpected error: %s' % error)

        logger.debug('Successful response %s', response)
        return response

    def amend(self, amend_requests):
        """
        Amend susbcriptions.
        """
        response = self.call(self.client.service.amend, amend_requests)
        return response

    def create(self, z_objects):
        """
        Create z_objects.
        """
        response = self.call(self.client.service.create, z_objects)
        return response

    def delete(self, object_string, ids=[]):
        """
        Delete z_objects by ID.
        """
        response = self.call(self.client.service.delete, object_string, ids)
        return response

    def execute(self, object_string, synchronous=False, ids=[]):
        """
        Execute a process by IDs.
        """
        response = self.call(self.client.service.execute, object_string,
                             synchronous, ids)
        return response

    def generate(self, z_objects):
        """
        Generate z_objects.
        """
        response = self.call(self.client.service.execute, z_objects)
        return response

    def get_user_info(self):
        """
        Return current user's info.
        """
        response = self.call(self.client.service.get_user_info)
        return response

    def login(self):
        """
        Login on the API to get a session.
        """
        response = self.client.service.login(self.username, self.password)
        self.set_session(response.Session)
        return response

    def query(self, query_string):
        """
        Execute a query.
        """
        response = self.call(self.client.service.query, query_string)
        return response

    def query_more(self, query_locator):
        """
        Execute the suite of a query.
        """
        response = self.call(self.client.service.queryMore, query_locator)
        return response

    def subscribe(self, subscribe_requests):
        """
        Subscribe accounts.
        """
        response = self.call(self.client.service.subscribe, subscribe_requests)
        return response

    def update(self, z_objects):
        """
        Update z_objects.
        """
        response = self.call(self.client.service.update, z_objects)
        return response

    def __str__(self):
        """
        Display the client __str__ method.
        """
        return self.client.__str__()
Exemple #4
0
class BaseZuora(object):
    """
    SOAP Client based on Suds
    """

    def __init__(self, wsdl, username, password,
                 session_duration=DEFAULT_SESSION_DURATION):
        self.wsdl = wsdl
        self.username = username
        self.password = password

        self.session = None
        self.session_duration = session_duration
        self.session_expiration = datetime.now()
        self.wsdl_path = 'file://%s' % os.path.abspath(self.wsdl)

        self.client = Client(
            self.wsdl_path,
            transport=HttpTransportWithKeepAlive())

    def instanciate(self, instance_type_string):
        """
        Create object for client.factory.
        """
        return self.client.factory.create(instance_type_string)

    def set_session(self, session_id):
        """
        Record the session info.
        """
        self.session = session_id
        self.session_expiration = datetime.now() + timedelta(
            seconds=self.session_duration)
        session_namespace = ('ns1', 'http://api.zuora.com/')
        session = Element('session', ns=session_namespace).setText(session_id)
        header = Element('SessionHeader', ns=session_namespace)
        header.append(session)
        self.client.set_options(soapheaders=[header])

    def reset(self):
        """
        Reset the connection to the API.
        """
        self.session = None
        self.client.options.transport = HttpTransportWithKeepAlive()

    def call(self, method, *args, **kwargs):
        """
        Call a SOAP method.
        """
        if self.session is None or self.session_expiration >= datetime.now():
            self.login()

        try:
            response = method(*args, **kwargs)
            logger.info('Sent: %s', self.client.last_sent())
            logger.info('Received: %s', self.client.last_received())
            if isinstance(response, Text):  # Occasionally happens
                logger.warning('Invalid response %s, retrying...', response)
                self.reset()
                return self.call(method, *args, **kwargs)
        except WebFault as error:
            if error.fault.faultcode == 'fns:INVALID_SESSION':
                logger.warning('Invalid session, relogging...')
                self.reset()
                return self.call(method, *args, **kwargs)
            else:
                logger.info('Sent: %s', self.client.last_sent())
                logger.info('Received: %s', self.client.last_received())
                logger.error('WebFault: %s', error.__dict__)
                raise ZuoraException('WebFault: %s' % error.__dict__)
        except Exception as error:
            logger.info('Sent: %s', self.client.last_sent())
            logger.info('Received: %s', self.client.last_received())
            logger.error('Unexpected error: %s', error)
            raise ZuoraException('Unexpected error: %s' % error)

        logger.debug('Successful response %s', response)
        return response

    def amend(self, amend_requests):
        """
        Amend susbcriptions.
        """
        response = self.call(
            self.client.service.amend,
            amend_requests)
        return response

    def create(self, z_objects):
        """
        Create z_objects.
        """
        response = self.call(
            self.client.service.create,
            z_objects)
        return response

    def delete(self, object_string, ids=[]):
        """
        Delete z_objects by ID.
        """
        response = self.call(
            self.client.service.delete,
            object_string, ids)
        return response

    def execute(self, object_string, synchronous=False, ids=[]):
        """
        Execute a process by IDs.
        """
        response = self.call(
            self.client.service.execute,
            object_string, synchronous, ids)
        return response

    def generate(self, z_objects):
        """
        Generate z_objects.
        """
        response = self.call(
            self.client.service.execute,
            z_objects)
        return response

    def get_user_info(self):
        """
        Return current user's info.
        """
        response = self.call(
            self.client.service.get_user_info)
        return response

    def login(self):
        """
        Login on the API to get a session.
        """
        response = self.client.service.login(self.username, self.password)
        self.set_session(response.Session)
        return response

    def query(self, query_string):
        """
        Execute a query.
        """
        response = self.call(
            self.client.service.query,
            query_string)
        return response

    def query_more(self, query_locator):
        """
        Execute the suite of a query.
        """
        response = self.call(
            self.client.service.queryMore,
            query_locator)
        return response

    def subscribe(self, subscribe_requests):
        """
        Subscribe accounts.
        """
        response = self.call(
            self.client.service.subscribe,
            subscribe_requests)
        return response

    def update(self, z_objects):
        """
        Update z_objects.
        """
        response = self.call(
            self.client.service.update,
            z_objects)
        return response

    def __str__(self):
        """
        Display the client __str__ method.
        """
        return self.client.__str__()
Exemple #5
0
logging.basicConfig(level=logging.INFO)

wsdl_url='https://api.orgregister.1c.ru/orgregister/v7?wsdl'

conf = {}
execfile("./1c-its.conf", conf) # reading username, password

transport = HttpAuthenticated(username=conf['username'],
                              password=conf['password'])
headers = {'Content-Type': 'text/xml; charset=utf-8'}
#client = Client(url=wsdl_url, transport=transport, headers=headers, plugins=[utf_doc_plugin(), UTFPlugin()])
client = Client(url=wsdl_url, transport=transport, headers=headers, plugins=[UTFPlugin()])

# It works!
print '----- client -----'
cli_str=client.__str__()
print cli_str.encode('utf8')
print '----- End of client -----'

# Service ( RequisitesWebServiceEndpointImpl2Service ) tns="http://ws.orgregister.company1c.com/"
#   Prefixes (3)
#      ns0 = "http://company1c.com/orgregister/corporation"
#      ns2 = "http://company1c.com/orgregister/entrepreneur"
#      ns3 = "http://ws.orgregister.company1c.com/"
#   Ports (1):
#      (RequisitesWebServiceEndpointImpl2Port)
#         Methods (3):
#            getCorporationRequisitesByINN(xs:string INN, xs:string configurationName, )
#            getCorporationRequisitesByNameAndAddress(xs:string name, xs:string regionCode, xs:string address, xs:string configurationName, )
#            getEntrepreneurRequisitesByINN(xs:string INN, xs:string configurationName, )
#         Types (30):
class ClientWrapper(object):
    """
    A custom wrapper of suds web service client for the monopond fax web services.
    Extends mapping utils to handle mapping of api objects to client objects.
    @ivar _client: suds client.
    @type _client:L{Client}
    """
    def __init__(self, url, username, password):
        self._client = Client(url)
        wsse_ns = ("wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd")
        mustAttribute = Attribute('SOAP-ENV:mustUnderstand', '1')
        security_header = Element("Security", ns=wsse_ns).append(mustAttribute)

        message_header = Element("UsernameToken", ns=wsse_ns)
        message_header.insert(Element("Username", ns=wsse_ns).setText(username))
        message_header.insert(Element("Password", ns=wsse_ns).setText(password))
        security_header.insert(message_header)
        self._client.set_options(soapheaders = security_header)

        self.mappingUtils = MappingUtils(self._client)

    def sendFax(self, request):
        if isinstance(request, SendFaxRequest) is False:
            raise TypeError, "%s incorrect request type" % (request.__class__)
        apiFaxDocuments = self.mappingUtils.mapDocumentListToApiFaxDocumentList(request.documents)
        apiFaxMessages = self.mappingUtils.mapFaxMessageListToApiFaxMessageList(request.faxMessages)
        apiFaxMessageBlocklist = None
        #if request.blocklists is not None:
            #apiFaxMessageBlocklist = self.mappingUtils.mapBlocklistsToApiFaxMessageBlocklist(request.blocklists)
        result = self._client.service.SendFax(BroadcastRef=request.broadcastRef, SendRef=request.sendRef,
            FaxMessages= apiFaxMessages, Documents=apiFaxDocuments, Resolution=request.resolution,
            Blocklists = apiFaxMessageBlocklist, Retries=request.retries, HeaderFormat=request.headerFormat)
        wrappedResult = self.mappingUtils.mapApiResponseToResponse(result)
        return wrappedResult

    def faxStatus(self, request):
        if isinstance(request, FaxStatusRequest) is False:
            raise TypeError, "%s incorrect request type" % (request.__class__)
        result = self._client.service.FaxStatus(MessageRef=request.messageRef, SendRef=request.sendRef,
            BroadcastRef=request.broadcastRef, Verbosity=request.verbosity)
        wrappedResult = self.mappingUtils.mapApiResponseToResponse(result)
        return wrappedResult

    def pauseFax(self, request):
        if isinstance(request, PauseFaxRequest) is False:
            raise TypeError, "%s incorrect request type" % (request.__class__)
        result = self._client.service.PauseFax(MessageRef=request.messageRef, SendRef=request.sendRef,
            BroadcastRef=request.broadcastRef)
        wrappedResult = self.mappingUtils.mapApiResponseToResponse(result)
        return wrappedResult

    def resumeFax(self, request):
        if isinstance(request, ResumeFaxRequest) is False:
            raise TypeError, "%s incorrect request type" % (request.__class__)
        result = self._client.service.ResumeFax(MessageRef=request.messageRef, SendRef=request.sendRef,
            BroadcastRef=request.broadcastRef)
        wrappedResult = self.mappingUtils.mapApiResponseToResponse(result)
        return wrappedResult

    def stopFax(self, request):
        if isinstance(request, StopFaxRequest) is False:
            raise TypeError, "%s incorrect request type" % (request.__class__)
        result = self._client.service.StopFax(MessageRef=request.messageRef, SendRef=request.sendRef,
            BroadcastRef=request.broadcastRef)
        wrappedResult = self.mappingUtils.mapApiResponseToResponse(result)
        print result
        return wrappedResult

    def getTypeInstance(self, typeName):
        return self._client.factory.create(typeName)

    def __str__(self):
        return self._client.__str__()
Exemple #7
0
logging.basicConfig(level=logging.INFO)

wsdl_url='https://api.orgregister.1c.ru/orgregister/v2?wsdl'

conf = {}
execfile("./1c-its.conf", conf) # reading username, password

transport = HttpAuthenticated(username=conf['username'],
                              password=conf['password'])
headers = {'Content-Type': 'text/xml; charset=utf-8'}
#client = Client(url=wsdl_url, transport=transport, headers=headers, plugins=[utf_doc_plugin(), UTFPlugin()])
client = Client(url=wsdl_url, transport=transport, headers=headers, plugins=[UTFPlugin()])

# It works!
print '----- client -----'
cli_str=client.__str__()
print cli_str.encode('utf8')
print '----- End of client -----'

# Service ( RequisitesWebServiceEndpointImpl2Service ) tns="http://ws.orgregister.company1c.com/"
#   Prefixes (3)
#      ns0 = "http://company1c.com/orgregister/corporation"
#      ns2 = "http://company1c.com/orgregister/entrepreneur"
#      ns3 = "http://ws.orgregister.company1c.com/"
#   Ports (1):
#      (RequisitesWebServiceEndpointImpl2Port)
#         Methods (3):
#            getCorporationRequisitesByINN(xs:string INN, xs:string configurationName, )
#            getCorporationRequisitesByNameAndAddress(xs:string name, xs:string regionCode, xs:string address, xs:string configurationName, )
#            getEntrepreneurRequisitesByINN(xs:string INN, xs:string configurationName, )
#         Types (30):
Exemple #8
0
class ClientWrapper(object):
    """
    A custom wrapper of suds web service client for the monopond fax web services.
    Extends mapping utils to handle mapping of api objects to client objects.
    @ivar _client: suds client.
    @type _client:L{Client}
    """
    def __init__(self, url, username, password):
        self._client = Client(url)
        wsse_ns = (
            "wsse",
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
        )
        mustAttribute = Attribute('SOAP-ENV:mustUnderstand', '1')
        security_header = Element("Security", ns=wsse_ns).append(mustAttribute)

        message_header = Element("UsernameToken", ns=wsse_ns)
        message_header.insert(
            Element("Username", ns=wsse_ns).setText(username))
        message_header.insert(
            Element("Password", ns=wsse_ns).setText(password))
        security_header.insert(message_header)
        self._client.set_options(soapheaders=security_header)

        self.mappingUtils = MappingUtils(self._client)

    def sendFax(self, request):
        if isinstance(request, SendFaxRequest) is False:
            raise TypeError, "%s incorrect request type" % (request.__class__)
        apiFaxDocuments = self.mappingUtils.mapDocumentListToApiFaxDocumentList(
            request.documents)
        apiFaxMessages = self.mappingUtils.mapFaxMessageListToApiFaxMessageList(
            request.faxMessages)
        apiFaxMessageBlocklist = None
        #if request.blocklists is not None:
        #apiFaxMessageBlocklist = self.mappingUtils.mapBlocklistsToApiFaxMessageBlocklist(request.blocklists)
        result = self._client.service.SendFax(
            BroadcastRef=request.broadcastRef,
            SendRef=request.sendRef,
            FaxMessages=apiFaxMessages,
            Documents=apiFaxDocuments,
            Resolution=request.resolution,
            Blocklists=apiFaxMessageBlocklist,
            Retries=request.retries,
            HeaderFormat=request.headerFormat)
        wrappedResult = self.mappingUtils.mapApiResponseToResponse(result)
        return wrappedResult

    def faxStatus(self, request):
        if isinstance(request, FaxStatusRequest) is False:
            raise TypeError, "%s incorrect request type" % (request.__class__)
        result = self._client.service.FaxStatus(
            MessageRef=request.messageRef,
            SendRef=request.sendRef,
            BroadcastRef=request.broadcastRef,
            Verbosity=request.verbosity)
        wrappedResult = self.mappingUtils.mapApiResponseToResponse(result)
        return wrappedResult

    def pauseFax(self, request):
        if isinstance(request, PauseFaxRequest) is False:
            raise TypeError, "%s incorrect request type" % (request.__class__)
        result = self._client.service.PauseFax(
            MessageRef=request.messageRef,
            SendRef=request.sendRef,
            BroadcastRef=request.broadcastRef)
        wrappedResult = self.mappingUtils.mapApiResponseToResponse(result)
        return wrappedResult

    def resumeFax(self, request):
        if isinstance(request, ResumeFaxRequest) is False:
            raise TypeError, "%s incorrect request type" % (request.__class__)
        result = self._client.service.ResumeFax(
            MessageRef=request.messageRef,
            SendRef=request.sendRef,
            BroadcastRef=request.broadcastRef)
        wrappedResult = self.mappingUtils.mapApiResponseToResponse(result)
        return wrappedResult

    def stopFax(self, request):
        if isinstance(request, StopFaxRequest) is False:
            raise TypeError, "%s incorrect request type" % (request.__class__)
        result = self._client.service.StopFax(
            MessageRef=request.messageRef,
            SendRef=request.sendRef,
            BroadcastRef=request.broadcastRef)
        wrappedResult = self.mappingUtils.mapApiResponseToResponse(result)
        print result
        return wrappedResult

    def getTypeInstance(self, typeName):
        return self._client.factory.create(typeName)

    def __str__(self):
        return self._client.__str__()